7

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!

4
  • 1
    Is this work string prefix = PREFIX_PATH; Commented Oct 25, 2016 at 10:23
  • 1
    string prefix = PREFIX_PATH; Commented Oct 25, 2016 at 10:24
  • PREFIX_PATH is already defined as a quoted string, but it is passed through VAL, which tries to quote the symbol again, with #. Also, note that non-Windows OS's usually use forward slashes, not backslashes as a path separator. Commented Oct 25, 2016 at 10:31
  • 2
    Your macro definitions are wrong. Commented Oct 25, 2016 at 10:37

3 Answers 3

7

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";
Sign up to request clarification or add additional context in comments.

Comments

7

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)";

2 Comments

"which I almost copied-and-pasted from your question" Almost? That's exactly what you've done :P
@LightnessRacesinOrbit: Not exactly, note the prefixPath instead of just prefix :)
2

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.

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.