C++14增加了quoted可以为输出字符串自动增加双引号:
string str1 = "hello";
cout<<str1<<endl; //输出:hello
cout<<quoted(str1)<<endl; //输出:"hello"
需要注意的是,quoted不是返回了一个增加了双引号字符串,他是一个ostream
操控器,它使用 >>
和 <<
运算符,使字符串能够方便地往返进出流。
string str1 = "hello";
string str2 = quoted(str1);
编译报错:
error: conversion from 'std::__detail::_Quoted_string<std::__cxx11::basic_string<char>&, char>' to non-scalar type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} requested
可以通过stringstream获取获取输出:
string str1 = "hello";
stringstream sstream;
sstream<<quoted(str1);
string&& str2 = sstream.str();
cout<<str2<<endl; //输出"hello"