有没有办法有多行纯文本,常量字面量在c++, à la Perl?也许是使用#include文件的一些解析技巧?我想不出一个,但那太好了。我知道是c++ 0x。
当前回答
你还可以这样做:
const char *longString = R""""(
This is
a very
long
string
)"""";
其他回答
你可以这样做:
const char *text = "This is my string it is "
"very long";
嗯…排序的。最简单的方法是使用相邻的字符串字面值由编译器连接的事实:
const char *text =
"This text is pretty long, but will be "
"concatenated into just a single string. "
"The disadvantage is that you have to quote "
"each part, and newlines must be literal as "
"usual.";
缩进并不重要,因为它不在引号内。
你也可以这样做,只要你注意转义嵌入的换行符。如果不这样做,就像我的第一个答案一样,将无法编译:
const char *text2 = "Here, on the other hand, I've gone crazy \ and really let the literal span several lines, \ without bothering with quoting each line's \ content. This works, but you can't indent.";
同样,注意每行末尾的反斜杠,它们必须在行结束之前,它们在源文件中转义换行符,这样就好像换行符不存在一样。你不会在有反斜杠的位置得到换行符。使用这种形式,您显然不能缩进文本,因为缩进将成为字符串的一部分,用随机空格混淆它。
选项1。使用boost库,可以如下所示声明字符串
const boost::string_view helpText = "This is very long help text.\n"
"Also more text is here\n"
"And here\n"
// Pass help text here
setHelpText(helpText);
第二个选项。如果boost在你的项目中不可用,你可以在现代c++中使用std::string_view()。
你还可以这样做:
const char *longString = R""""(
This is
a very
long
string
)"""";
在c++ 11中,你有原始字符串字面值。有点像这里-文本在shell和脚本语言,如Python、Perl和Ruby。
const char * vogon_poem = R"V0G0N(
O freddled gruntbuggly thy micturations are to me
As plured gabbleblochits on a lurgid bee.
Groop, I implore thee my foonting turlingdromes.
And hooptiously drangle me with crinkly bindlewurdles,
Or I will rend thee in the gobberwarts with my blurlecruncheon, see if I don't.
(by Prostetnic Vogon Jeltz; see p. 56/57)
)V0G0N";
字符串中的所有空格、缩进和换行符都被保留。
这些也可以是utf-8|16|32或wchar_t(带有常用的前缀)。
我应该指出,这里实际上不需要转义序列V0G0N。它的存在将允许将)“放入字符串中。换句话说,我可以把
"(by Prostetnic Vogon Jeltz; see p. 56/57)"
(注意额外的引号)和上面的字符串仍然是正确的。否则我还不如用
const char * vogon_poem = R"( ... )";
引号内的括号仍然是需要的。
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?
- 为什么std::map被实现为红黑树?