Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from #define to string c++

I would like to convert from #define to string.

My code:

#ifdef WIN32
#define PREFIX_PATH = "..\\"
#else
#define PREFIX_PATH = "..\\..\\"
#endif


#define VAL(str) #str
#define TOSTRING(str) VAL(str)

string prefix = TOSTRING(PREFIX_PATH);
string path = prefix + "Test\\Input\input.txt";

But, it didn't work..

prefix value is "..\\\"

Any idea what is the problem..

Thanks!

like image 439
Programmer Avatar asked Jul 16 '26 12:07

Programmer


2 Answers

You don't need "=" in defines, or any #str, or "+" between double quoted strings.

#ifdef WIN32
    #define PREFIX_PATH "..\\"
#else
    #define PREFIX_PATH "..\\..\\"
#endif

string path = PREFIX_PATH "Test\\Input\\input.txt";
like image 98
user31264 Avatar answered Jul 19 '26 00:07

user31264


What about something simpler like that?

#ifdef WIN32
const std::string prefixPath = "..\\";
#else
const std::string prefixPath = "..\\..\\";
#endif

std::string path = prefixPath + "Test\\Input\\input.txt";

PS You may have a typo in the last line, in which you may miss another \ before input.txt.

As an alternative, if your C++ compiler supports this C++11 feature, you may want to use raw string literals, so you can have unescaped \, e.g.:

std::string path = prefixPath + R"(Test\Input\input.txt)";
like image 40
Mr.C64 Avatar answered Jul 19 '26 01:07

Mr.C64



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!