原始字面量
原始字面量
R “xxx(原始字符串)xxx”
一个例子直接带入
#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
在R “xxx(raw string)xxx” 中,原始字符串必须用括号()括起来,括号的前后可以加其他字符串,所加的字符串会被忽略,并且加的字符串必须在括号两边同时出现。
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1 = R"(D:\hello\world\test.text)";
cout << str1 << endl;
string str2 = R"luffy(D:\hello\world\test.text)luffy";
cout << str2 << endl;
#if 0
string str3 = R"luffy(D:\hello\world\test.text)robin"; // 语法错误,编译不通过
cout << str3 << endl;
#endif
return 0;
}
D:\hello\world\test.text
D:\hello\world\test.text
结论:使用原始字面量R “xxx(raw string)xxx”,()两边的字符串在解析的时候是会被忽略的,因此一般不用指定。如果在()前后指定了字符串,那么前后的字符串必须相同,否则会出现语法错误。