原始字面量

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() 中的内容来描述路径的字符串,因此无需做任何处理;
posted @ 2025-12-11 09:44  ProMonkey;  阅读(8)  评论(0)    收藏  举报