C++11 R字符串原始字面量

本文介绍了C++中原始字符串字面量的使用方法,包括如何避免转义字符的影响,以及如何跨越多行定义字符串。通过示例展示了普通字符串与原始字符串的区别。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

原始字符串字面量的定义为:R “xxx(raw string)xxx”
其中,原始字符串必须用括号()括起来,括号的前后可以加其他字符串,所加的字符串会被忽略,并且加的字符串必须在括号两边同时出现。

#include <iostream>
#include <string>

int main()
{
    // 一个普通的字符串,'\n'被当作是转义字符,表示一个换行符。
    std::string normal_str = "First line.\nSecond line.\nEnd of message.\n";
	---输出:
	First line.
	Second line.
	End of message.

    // 一个raw string,'\'不会被转义处理。因此,"\n"表示两个字符:字符反斜杠 和 字母n。
    std::string raw_str = R"(First line.\nSecond line.\nEnd of message.\n)";
	---输出:
	First line.\nSecond line.\nEnd of message.\n
	
    std::cout << normal_str << std::endl;
    std::cout << raw_str << std::endl;
    std::cout << R"foo(Hello, world!)foo" << std::endl;
	---输出:
	Hello, world!

    // raw string可以跨越多行,其中的空白和换行符都属于字符串的一部分。
    std::cout <<R"(
                   Hello,
                   world!
                   )" << std::endl;
	---输出:
	
                   Hello,
                   world!


    return 0;
}

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值