Reputation: 381
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!
Upvotes: 7
Views: 17674
Reputation: 6727
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";
Upvotes: 7
Reputation: 42924
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)";
Upvotes: 7
Reputation: 2507
Although I'd highly recommend Mr.C64's approach, but if you want to use define for some reason then,
#ifdef WIN32
#define PREFIX_PATH "..\\"
#else
#define PREFIX_PATH "..\\..\\"
#endif
std::string prefix = PREFIX_PATH;
std::string path = PREFIX_PATH + "Test\\Input\\input.txt";
For #define you don't put an equals between key and value, and the TOSTRING function was unnecessary. #define is just find-replace so thinking in those terms might help you use it.
Upvotes: 2