std::quoted
来自cppreference.com
| 在标头 <iomanip> 定义
|
||
| |
(1) | (C++14 起) |
| |
(2) | (C++14 起) |
| |
(3) | (C++17 起) |
| |
(4) | (C++14 起) |
允许插入或提取带引号字符串,例如在 CSV 或 XML 中出现的那些。
1-3) 用于表达式
out << quoted(s, delim, escape) 时,其中 out 为拥有等于 CharT 的 char_type 的输出流,且对于重载 (2,3),其 traits_type 等于 Traits,表现为有格式输出函数 (FormattedOutputFunction) ,它将以如下方式构造的字符序列 seq 插入到 out:a) 首先,向序列添加字符
delim。b) 然后是
s 中的每个字符,但若下个要输出的字符等于 delim 或等于 escape(以流的 traits_type::eq 确定),则首先后附一个额外的 escape 副本。c) 最后,再次向
seq 后附 delim。- 然后,若
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 的效果,若存在。
4) 用于表达式
in >> quoted(s, delim, escape) 中时,其中 in 是拥有等于 CharT 的 char_type 和等于 Traits 的 traits_type 的输入流时,用 std::basic_istream::operator>> 按照下列规则从 in 提取字符:a) 若首个提取的字符不等于
delim(以流的 traits_type::eq 确定),则简单地进行 in >> s。b) 否则(若首字符是分隔符):
1) 关闭输入流上的 skipws 标志。
2) 通过调用
s.clear() 清空目标字符串。3) 从
in 提取连续字符并将它们追加到 s,但每当提取到 escape 字符,就忽略该字符并后附下个字符到 s。!in == true 时或找到未转义的 delim 字符时停止提取。4) 舍弃最终(未转义)的
delim 字符。5) 恢复输入流上的 skipws 标志为其原值。
参数
| s | - | 要插入或提取的字符串 |
| delim | - | 用作分隔符的字符,默认为 "
|
| escape | - | 用作转义字符的字符,默认为 \
|
返回值
返回未指定类型对象,使得上述行为发生。
异常
若 operator>> 或 operator<< 抛出异常则抛出 std::ios_base::failure。
示例
运行此代码
#include <iomanip>
#include <iostream>
#include <sstream>
void default_delimiter()
{
const std::string in = "std::quoted() quotes this string and embedded \"quotes\" too";
std::stringstream ss;
ss << std::quoted(in);
std::string out;
ss >> std::quoted(out);
std::cout << "默认分隔符的情形:\n"
"读取为 [" << in << "]\n"
"存储为 [" << ss.str() << "]\n"
"写出为 [" << out << "]\n\n";
}
void custom_delimiter()
{
const char delim{'$'};
const char escape{'%'};
const std::string in = "std::quoted() quotes this string and embedded $quotes$ $too";
std::stringstream ss;
ss << std::quoted(in, delim, escape);
std::string out;
ss >> std::quoted(out, delim, escape);
std::cout << "自定义分隔符的情形:\n"
"读取为 [" << in << "]\n"
"存储为 [" << ss.str() << "]\n"
"写出为 [" << out << "]\n\n";
}
int main()
{
default_delimiter();
custom_delimiter();
}
输出:
默认分隔符的情形:
读取为 [std::quoted() quotes this string and embedded "quotes" too]
存储为 ["std::quoted() quotes this string and embedded \"quotes\" too"]
写出为 [std::quoted() quotes this string and embedded "quotes" too]
自定义分隔符的情形:
读取为 [std::quoted() quotes this string and embedded $quotes$ $too]
存储为 [$std::quoted() quotes this string and embedded %$quotes%$ %$too$]
写出为 [std::quoted() quotes this string and embedded $quotes$ $too]
参阅
(C++20) |
在新字符串中存储参数的格式化表示 (函数模板) |