有没有办法有多行纯文本,常量字面量在c++, à la Perl?也许是使用#include文件的一些解析技巧?我想不出一个,但那太好了。我知道是c++ 0x。
当前回答
// 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";
其他回答
为了在@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的简短评论在我第一次读到这篇文章时并没有跳入我的脑海,所以我必须自己去发现。希望我为其他人节省了几分钟时间。
输入多行字符串可能很方便的方法是使用宏。这只适用于引号和括号平衡,并且不包含“顶级”逗号的情况:
#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__允许使用,。
你可以这样做:
const char *text = "This is my string it is "
"very long";
选项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 *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.";
同样,注意每行末尾的反斜杠,它们必须在行结束之前,它们在源文件中转义换行符,这样就好像换行符不存在一样。你不会在有反斜杠的位置得到换行符。使用这种形式,您显然不能缩进文本,因为缩进将成为字符串的一部分,用随机空格混淆它。