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.
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.
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);
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.
results5.txtout 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 achar filename[PATH_MAX]and asprintf()call for the basic need you're trying to fill.