在 C++ 中声明多行字符串
本文将介绍几种在 C++ 中如何声明多行字符串的方法。
使用 std::string
类在 C++ 中声明多行字符串
std::string
对象可以用一个字符串值初始化。在这种情况下,我们将 s1
字符串变量声明为 main
函数的一个局部变量。C++ 允许在一条语句中自动连接多个双引号的字符串字元。因此,在初始化 string
变量时,可以包含任意行数,并保持代码的可读性更一致。
#include <iostream>#include <string>#include <vector>#include <iterator>using std::cout; using std::vector;
using std::endl; using std::string;
using std::copy;
int main(){
string s1 = "This string will be printed as the"
" one. You can include as many lines"
"as you wish. They will be concatenated";
copy(s1.begin(), s1.end(),
std::ostream_iterator<char>(cout, ""));
cout << endl;
return EXIT_SUCCESS;
}
输出:
This string will be printed as the one. You can include as many linesas you wish. They will be concatenated
使用 const char *
符号来声明多行字符串文字
但在大多数情况下,用 const
修饰符声明一个只读的字符串文字可能更实用。当相对较长的文本要输出到控制台,而且这些文本大多是静态的,很少或没有随时间变化,这是最实用的。需要注意的是,const
限定符的字符串在作为 copy
算法参数传递之前需要转换为 std::string
对象。
#include <iostream>#include <string>#include <vector>#include <iterator>using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::copy;
int main(){
const char *s2 =
"This string will be printed as the"
" one. You can include as many lines"
"as you wish. They will be concatenated";
string s1(s2);
copy(s1.begin(), s1.end(),
std::ostream_iterator<char>(cout, ""));
cout << endl;
return EXIT_SUCCESS;
}
输出:
This string will be printed as the one. You can include as many linesas you wish. They will be concatenated
使用 const char *
符号与反斜杠字声明多行字符串文字
另外,也可以利用反斜杠字符/
来构造一个多行字符串文字,并将其分配给 const
限定的 char
指针。简而言之,反斜杠字符需要包含在每个换行符的末尾,这意味着字符串在下一行继续。
不过要注意,间距的处理变得更容易出错,因为任何不可见的字符,如制表符或空格,可能会将被包含在输出中。另一方面,人们可以利用这个功能更容易地在控制台显示一些模式。
#include <iostream>#include <string>#include <vector>#include <iterator>using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::copy;
int main(){
const char *s3 = " This string will\n\
printed as the pyramid\n\
as one single string literal form\n";
cout << s1 << endl;
printf("%s\n", s3);
return EXIT_SUCCESS;
}
输出:
This string will
printed as the pyramid
as one single string literal form
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。