How to create strings using c / C ++ macro arguments

I am 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); 

Can this be done like that? What's wrong? Thanks.

+4
source share
3 answers

WITH

Since you marked C and want to use a macro solution, use # in the macro

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

Be careful, therefore you cannot use variables.

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

Otherwise, you must use functions to use variables.


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); 
+4
source

You marked your question with both C and C++ . For the C++ part, the easiest way is:

 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, for this you would probably use a nicer name than the all-uppercase FILENAME .

+1
source
 #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 
0
source

All Articles