Pro*_*mer 3 c++ string c-preprocessor
我想从#define转换为string.
我的代码:
#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";
Run Code Online (Sandbox Code Playgroud)
但是,它没有用..
前缀值为".. \\\"
不知道是什么问题..
谢谢!
定义中不需要“=”,也不需要任何#str,或者双引号字符串之间的“+”。
#ifdef WIN32
#define PREFIX_PATH "..\\"
#else
#define PREFIX_PATH "..\\..\\"
#endif
string path = PREFIX_PATH "Test\\Input\\input.txt";
Run Code Online (Sandbox Code Playgroud)
那样简单的事情怎么样?
#ifdef WIN32
const std::string prefixPath = "..\\";
#else
const std::string prefixPath = "..\\..\\";
#endif
std::string path = prefixPath + "Test\\Input\\input.txt";
Run Code Online (Sandbox Code Playgroud)
PS你可能在最后一行有一个拼写错误,你\之前可能会错过另一个拼写错误input.txt.
作为替代方案,如果您的C++编译器支持此C++ 11功能,您可能希望使用原始字符串文字,因此您可以使用非转义\,例如:
std::string path = prefixPath + R"(Test\Input\input.txt)";
Run Code Online (Sandbox Code Playgroud)