4

I'm trying to achieve this:

char * fname = "results5.txt"

Using a macro like this:

#define FILENAME(NUM) "results" NUM ".txt"

int number = 5;
char * fname = FILENAME(number);

It's possible to do it that way? What's wrong? Thanks.

3
  • 7
    If you want results5.txt out of that, I'm afraid the preprocesor isn't going to rescue you. Regarding what is wrong? Lookup "How a C program is compiled", paying close attention to the preprocessing phase. @duDE I think you're going to need a char filename[PATH_MAX] and a sprintf() call for the basic need you're trying to fill. Commented Apr 16, 2013 at 14:55
  • 3
    Why can't you use a function at runtime? Commented Apr 16, 2013 at 14:55
  • If you want to change this sort of information at compile time you can use -D to pass in a value. g++ ... -DFILENAME="results5.txt" char* fname = FILENAME; Commented Apr 16, 2013 at 15:10

3 Answers 3

5

C

Since you tagged C and want macro based solution, use a # in the macro

#define FILENAME(NUM) "results"#NUM".txt"
                               ^^^^^
char *fname = FILENAME(5);

Be careful in this way you can not use variables.

int number = 5;
char *fname = FILENAME(number); // IMPOSSIBLE

Otherwise, to use variables, you should use functions.


C++

made everything easier

std::string FileName(int d)
{
    return "results"+ std::to_string(d) +".txt";

    //  or...
    //  std::ostringstream str;
    //  str << "results" << d << ".txt";
    //  return str.str();
}

...

int number = 5;
std::string filename = FileName(number);
Sign up to request clarification or add additional context in comments.

Comments

1

You've tagged your question both C and C++. For the C++ part, the easiest would be:

inline std::string FILENAME(int number) {
  std::ostringstream s;
  s << "results" << number << ".txt";
  return s.str();
}



int number = 5;
std::string fname = FILENAME(number);

Of course, you'd probably use a nicer name than all-uppercase FILENAME for this.

Comments

0
#include <sstream>
#include <string>

int number = 5;
std::stringstream ss;
ss << "results" << number << ".txt"
std::string filename = ss.str(); //if you need it as C++ string
char const* filename = ss.str().c_str(); //if you need it as C string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.