新的C++标准可以在代码里嵌入一段原始字符串,该原始字符串不作任何转义,所见即所得,这个特性对于编写代码时要输入多行字符串,或者含引号的字符串提供了巨大方便。

先介绍特性如下:

原始字符串的开始符号 :R"(  , 原始字符串的结束符号:)"R"   (  之间可以插入其它任意字符串。

1、不做任何转义

std::string str1 = "aaaaaa.\nbbbb.\ncccc.\n";

cout << str1 <<endl;


cout << "---------------------" <<endl;

std::string raw_str = R"(aaaaaa\nbbbb\ncccc\n)";

cout << raw_str <<endl;

将输出:

aaaaaa
bbbb
cccc
---------------------

aaaaaa\nbbbb\ncccc\n

其中 str1 是常规的C++字符串,对\n 进行了转义,而raw_str没有进行任何转义,所见即所得。

二、可以输入多行文本

const std::string json_text = R"(
    {
        "name": "Judd Trump",
        "credits": 1754500,
        "ranking": 1
    }
)";

j = json.parse(json_text)

原始字符串的表达形式:

原始字符串的定义形式为:R"xxx(raw string text)xxx"
其中,原始字符串必须用括号()括起来,括号的前后可以加任意其它相同的字符串,所加的字符串会被编译器忽略。

	const std::string json_text = R"(
    {
        "name": "Judd Trump",
        "credits": 1754500,
        "ranking": 1
    }
)";

	const std::string json_text2 = R"AAA(
    {
        "name": "Judd Trump",
        "credits": 1754500,
        "ranking": 1
    }
)AAA";


    std::cout << json_text;

	std::cout << json_text2;

备注:以上代码里 json_text 与 json_text2的内容一样。

输出结果如下:

   
   {
        "name": "Judd Trump",
        "credits": 1754500,
        "ranking": 1
    }
 

    {
        "name": "Judd Trump",
        "credits": 1754500,
        "ranking": 1
    }
 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐