C++ 你能把#define's 扩展成字符串文字吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1079020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you expand #define's into string literals?
提问by Adam Naylor
Is there a way to get the C++ pre-processor to expand a #define'ed value into a string literal?
for example:
有没有办法让 C++ 预处理器将 #define 的值扩展为字符串文字?
例如:
#define NEW_LINE '\n'
Printf("OutputNEW_LINE"); //or whatever
This looks to me like it should be possible as it's before compilation?
Or is there a better design pattern to achieve this kind of behaviour (without resorting to runtime fixes like sprintf)?
这在我看来应该是可能的,就像在编译之前一样?
或者是否有更好的设计模式来实现这种行为(无需求助于 sprintf 之类的运行时修复)?
EDITI understand that #define's can be evil, but for arguments sake...
编辑我知道#define's 可能是邪恶的,但为了争论......
ADDITIONALDoes anyone have any criticism of this approach?
附加有没有人对这种方法有任何批评?
回答by RichieHindle
This will do it:
这将做到:
#define NEW_LINE "\n" // Note double quotes
Printf("Output" NEW_LINE);
(Technically it's the compiler joining the strings rather than the preprocessor, but the end result is the same.)
(从技术上讲,是编译器连接字符串而不是预处理器,但最终结果是相同的。)
回答by Thomas Freudenberg
If I remember correctly it is
如果我没记错的话是
Printf("Output" NEW_LINE);
回答by avakar
You can do the following.
您可以执行以下操作。
#define NEW_LINE "\n"
printf("Output" NEW_LINE);
回答by Kosi2801
#define NEW_LINE "\n"
printf("Output" NEW_LINE); //or whatever
should do the trick.
应该做的伎俩。
回答by Domas Mituzas
Well....
好....
printf("Output%s", NEW_LINE);