std::quoted
在标头 <iomanip> 定义
|
||
template< class CharT > /*unspecified*/ quoted(const CharT* s, |
(1) | (C++14 起) |
template< class CharT, class Traits, class Allocator > /*unspecified*/ quoted(const std::basic_string<CharT, Traits, Allocator>& s, |
(2) | (C++14 起) |
template< class CharT, class Traits> /*unspecified*/ quoted(std::basic_string_view<CharT, Traits> s, |
(3) | (C++17 起) |
template< class CharT, class Traits, class Allocator > /*unspecified*/ quoted(std::basic_string<CharT, Traits, Allocator>& s, |
(4) | (C++14 起) |
允许插入或释出带引号字符串,例如在 CSV 或 XML 中找到者。
用于表达式 out << quoted(s, delim, escape) ,其中 out
为拥有等于 CharT
的 char_type
的输出流,对于重载 2-4 ,还拥有等于 Traits
的 traits_type
时,表现为有格式输出函数 (FormattedOutputFunction) ,它插入以如下方式构造的字符序列 seq
到 out :
delim
到序列s
的字符,除了若下个要输出的字符等于 delim
或等于 escape
(以流的 traits_type::eq
确定),则首先后附 escape
的额外副本delim
多一次到 seq
然后,若 seq.size() < out.width()
,则添加 out.width()-seq.size()
个填充字符 out.fill()
副本到序列的末尾(若 out.flags()
中设置了 ios_base::left
)或到序列的起始(所有其他情况下)。
最后,如同以调用 out.rdbuf()->sputn(seq, n) 输出来自每个结果序列的字符,其中 n=std::max(out.width(), seq.size()) ,并调用 out.width(0) 取消 std::setw 的效果,若存在。
in
是拥有等于 CharT
的 char_type
和等于 Traits
的 traits_type
输入流时,用 std::basic_istream::operator>> 按照下列规则从 in 释出字符:delim
(以流的 traits_type::eq
确定),则简单地进行 in >> s 。in
释出字符并后附字符到 s
,除了凡在释出 escape
字符时,忽略该字符并后附下个字符到 s
。 !in==true 时或找到未转义的 delim
字符时释出停止。delim
字符。参数
s | - | 要插入或释出的字符串 |
delim | - | 用作分隔符的字符,默认为 "
|
escape | - | 用作转义字符的字符,默认为 \
|
返回值
返回未指定类型对象,使得上述行为发生。
异常
若 operator>>
或 operator<<
抛出则抛出 std::ios_base::failure 。
示例
#include <iostream> #include <iomanip> #include <sstream> int main() { std::stringstream ss; std::string in = "String with spaces, and embedded \"quotes\" too"; std::string out; auto show = [&](const auto& what) { &what == &in ? std::cout << "read in [" << in << "]\n" << "stored as [" << ss.str() << "]\n" : std::cout << "written out [" << out << "]\n\n"; }; ss << std::quoted(in); show(in); ss >> std::quoted(out); show(out); ss.str(""); // clear the stream buffer in = "String with spaces, and embedded $quotes$ too"; const char delim {'$'}; const char escape {'%'}; ss << std::quoted(in, delim, escape); show(in); ss >> std::quoted(out, delim, escape); show(out); }
输出:
read in [String with spaces, and embedded "quotes" too] stored as ["String with spaces, and embedded \"quotes\" too"] written out [String with spaces, and embedded "quotes" too] read in [String with spaces, and embedded $quotes$ too] stored as [$String with spaces, and embedded %$quotes%$ too$] written out [String with spaces, and embedded $quotes$ too]