c++11原始字面量

19 篇文章 0 订阅

在 C++11 中添加了定义原始字符串的字面量,**定义方式为:R “xxx(原始字符串)xxx” 其中()两边的字符串可以省略。**原始字面量 R 可以直接表示字符串的实际含义,而不需要额外对字符串做转译或连接等操作。
注意:在R “xxx(raw string)xxx” 中,原始字符串必须用括号()括起来,括号的前后可以加其他字符串,所加的字符串会被忽略,并且加的字符串必须在括号两边同时出现。

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str = "D:\hello\world\test.txt";
    cout << str << endl;
    string str1 = "D:\\hello\\world\\test.txt";
    cout << str1 << endl;
    string str2 = R"(D:\hello\world\test.txt)";
    cout << str2 << endl;

    return 0;
}

输出的结果:

$ ./demo2 
D:helloworld    est.txt
D:\hello\world\test.txt
D:\hello\world\test.txt

在 D:\hello\world\test.txt 中 \h 和 \w 转译失败,对应的字符会原样输出
在 D:\hello\world\test.txt 中路径的间隔符为 \ 但是这个字符又是转译字符,因此需要使用转译字符将其转译,最终才能得到一个没有特殊含义的普通字符
在 R"(D:\hello\world\test.txt)" 使用了原始字面量 R()中的内容就是描述路径的原始字符串,无需做任何处理
通过测试可以看到,使用原始字面量 R 可以直接得到其原始意义的字符串

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str1 = R"(D:\hello\world\test.txt)";
    cout << str1 << endl;
    string str2 = R"lucky(D:\hello\world\test.txt)lucky";
    cout << str2 << endl;
    //string str3 = R"lucky(D:\hello\world\test.txt)happy";	// 语法错误,编译不通过
    //cout << str3 << endl;
    return 0;
}

在 C++11 之前如果一个字符串分别写到了不同的行里边,需要加连接符,这种方式不仅繁琐,还破坏了表达式的原始含义,如果使用原始字面量就变得简单很多,很强直观,可读性强。

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str = "<html>\
        <head>\
        <title>\
        海贼王\
        </title>\
        </head>\
        <body>\
        <p>\
        我是要成为海贼王的男人!!!\
        </p>\
        </body>\
        </html>";
    cout << str << endl;
    return 0;
}

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str = R"(<html>
        <head>
        <title>
        海贼王
        </title>
        </head>
        <body>
        <p>
        我是要成为海贼王的男人!!!
        </p>
        </body>
        </html>)";
    cout << str << endl;

    return 0;
}

输出对比:
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值