有没有办法有多行纯文本,常量字面量在c++, à la Perl?也许是使用#include文件的一些解析技巧?我想不出一个,但那太好了。我知道是c++ 0x。
当前回答
选项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()。
其他回答
输入多行字符串可能很方便的方法是使用宏。这只适用于引号和括号平衡,并且不包含“顶级”逗号的情况:
#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
Using this trick(,) you don't need to use quotes.
Though newlines and multiple white spaces
will be replaced by a single whitespace.
);
printf("[[%s]]\n",text);
使用gcc 4.6或g++ 4.6编译,会生成:[[使用这个技巧(,)你不需要使用引号。虽然换行符和多个空格将被单个空格取代。
注意,不能在字符串中,除非它包含在括号或引号中。可以使用单引号,但会产生编译器警告。
编辑:正如评论中提到的,#define MULTI_LINE_STRING(…)#__VA_ARGS__允许使用,。
为了在@unwind的回答中稍微说明一下@emsr的注释,如果一个人不够幸运,没有c++ 11编译器(比如GCC 4.2.1),并且他想在字符串中嵌入换行符(char *或类字符串),他可以这样写:
const char *text =
"This text is pretty long, but will be\n"
"concatenated into just a single string.\n"
"The disadvantage is that you have to quote\n"
"each part, and newlines must be literal as\n"
"usual.";
很明显,这是真的,但是@emsr的简短评论在我第一次读到这篇文章时并没有跳入我的脑海,所以我必须自己去发现。希望我为其他人节省了几分钟时间。
// C++11.
std::string index_html=R"html(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VIPSDK MONITOR</title>
<meta http-equiv="refresh" content="10">
</head>
<style type="text/css">
</style>
</html>
)html";
在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"( ... )";
引号内的括号仍然是需要的。
选项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()。
推荐文章
- c++中size_t和int的区别是什么?
- 在C和c++中静态变量存储在哪里?
- 为什么标准迭代器范围是[begin, end]而不是[begin, end]?
- c++双地址操作符?(& &)
- python: SyntaxError: EOL扫描字符串文字
- 函数标题中的箭头操作符(->)
- 如何在c++中初始化一个向量
- 返回类型为'?:'(三元条件运算符)
- 当分配vector时,它们使用的是堆上的内存还是堆栈上的内存?
- 互斥实例/教程?
- 如何添加一个'或'条件在#ifdef
- 纯虚函数的实现
- 为什么在c++中声明enum时使用typedef ?
- 对静态类成员的未定义引用
- c++中“using”关键字背后的逻辑是什么?