C++ 中存在轉義字符,例如"\n"或"\t"。當我們嘗試打印轉義字符時,它們不會顯示在輸出中。為了在輸出屏幕上顯示轉義字符,我們使用了"R(帶轉義字符的字符串)"作為原始字符串字面量。在字符串前面使用 R 後,轉義字符將顯示在輸出中。
定義方式: R "xxx(原始字符串)xxx"
其中()兩邊的xxx要一樣包括長度、順序;
xxx在編譯時會被忽略,對括號中的字符串沒有影響,一般xxx用途相當於註釋這個字符串的用途,因此一般不用指定
原始字符串必須用括號()括起來。
例如:當我們要打印一個路徑時,由於路徑字符串中常常包含一些特殊字符,傳統方法通常需要使用轉義字符 '\' 來處理。但如果使用原始字符串字面量,就可以輕鬆解決這個問題。
#include <iostream>
using namespace std;
int main(){
string str = "E:\wwh\c++\temp\cpp_new_features";
cout << str << endl;
string str1 = "E:\\wwh\\c++\\temp\\cpp_new_features";
cout << str1 << endl;
string str2 = R"(E:\wwh\c++\temp\cpp_new_features)";
cout << str2 << endl;
string str3 = R"123abc(E:\wwh\c++\temp\cpp_new_features)123abc";
cout << str3 << endl;
system("pause");
return 0;
}
輸出結果:
E:wwhc++ empcpp_new_features
E:\wwh\c++\temp\cpp_new_features
E:\wwh\c++\temp\cpp_new_features
E:\wwh\c++\temp\cpp_new_features
- 第一條語句中,\h 和 \w 轉義失敗,對應地字符串會原樣輸出;
- 第二條語句中,是在沒有原始字面量的時候比較常見的操作,第一個反斜槓對第二個反斜槓的轉義,'\\'表示’\';
- 第三條語句中,使用了原始字面量 R() 中的內容來描述路徑的字符串,因此無需做任何處理;
- 第四條語句中,括號兩邊加入xxx,不同會報錯,編譯會忽略。
在 C++11 之前如果一個字符串分別寫到了不同行裏,需要加連接符'\',這種方式不僅繁瑣,還破壞了表達式的原始含義,如果使用原始字面量就變得簡單很多,很強直觀,可讀性強。我們通過一個輸出 HTML 標籤的例子體會一下原始字面量。
#include <iostream>
using namespace std;
int main(){
string str = "<html>\
<head>\
<title>\
原始字面量\
</title>\
</head>\
<body>\
<p>\
C++11字符串原始字面量\
</p>\
</body>\
</html>";
cout << str << endl;
string str1 = "< html > \n\
<head>\n\
<title>\n\
原始字面量\n\
< / title>\n\
< / head>\n\
<body>\n\
<p>\n\
C++11字符串原始字面量\n\
</p>\n\
</body>\n\
</html>";
cout << str1 << endl;
string str2 = R"(<html>
<head>
<title>
原始字面量
</title>
</head>
<body>
<p>
C++11字符串原始字面量
</p>
</body>
</html> )";
cout << str2 << endl;
system("pause");
return 0;
}
輸出結果:
<html> <head> <title> 原始字面量 </title> </head> <body> <p> C++11字符串原始字面量 </p> </body> </html>
< html >
<head>
<title>
原始字面量
< / title>
< / head>
<body>
<p>
C++11字符串原始字面量
</p>
</body>
</html>
<html>
<head>
<title>
原始字面量
</title>
</head>
<body>
<p>
C++11字符串原始字面量
</p>
</body>
</html>
- 第一條語句中,每個換行加'\',但是實際輸出沒有換行;
- 第二條語句中,在第一條語句基礎上加上了換行符'\n';
- 第三條語句中,使用了原始字面量 R() 中的內容來描述路徑的字符串,因此無需做任何處理;