C/C++中如果需要在字符串中显示双引号回车换行等,需要进行转义:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s1 = "\"hello\"";
string s2 = "Hi\nWhat's up";
cout<<s1<<endl;
cout<<s2<<endl;
return 0;
}
运行程序输出:
"hello"
Hi
What's up
C++11引入了原始字符串,格式为R"(raw string text)",更加方便处理需要进行转义的字符串:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s1 = R"("hello")";
string s2 = R"(Hi
What's up)";
cout<<s1<<endl;
cout<<s2<<endl;
return 0;
}
运行程序输出:
"hello"
Hi
What's up
可以看到,原始字符串会安装其在程序中的样子进行输出。