在C++11中添加了定义原始字符串的字面量,定义方式为:R “xxx(原始字符串)xxx”其中()两边的字符串可以省略。原始字面量R可以直接表示字符串的实际含义,而不需要额外对字符串做转义或连接等操作。
比如:编程过程中,使用的字符串中常带有一些特殊字符,对于这些字符往往要做专门的处理,使用了原始字面量就可以轻松的解决这个问题了,比如打印路径:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str = "D:\hello\world\test.text";
cout << str << endl;
string str1 = "D:\\hello\\world\\test.text";
cout << str1 << endl;
string str2 = R"(D:\hello\world\test.text)";
cout << str2 << endl;
return 0;
}
输出的结果为:
D:helloworld est.text
D:\hello\world\test.text
D:\hello\world\test.text
- 在D:\hello\world\test.text中\h和\w转义失败,对应的字符会原样输出
- 在D:\\hello\\world\\test.text中路径的间隔符为\但是这个字符又是转义字符,因此需要使用转义