operator<<,>>(std::basic_string)
来自 cppreference.cn
< cpp | string | basic_string
定义于头文件 <string> |
||
template< class CharT, class Traits, class Allocator > std::basic_ostream<CharT, Traits>& |
(1) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& |
(2) | |
1) 行为如同一个 FormattedOutputFunction。在构造并检查哨兵对象后,确定输出格式填充。
然后将结果序列 seq(str 的内容加填充)中的每个字符插入到输出流 os,如同调用 os.rdbuf()->sputn(seq, n),其中 n 是 std::max(os.width(), str.size())。最后,调用 os.width(0) 以取消 std::setw(如果有)的效果。
等价于 return os << std::basic_string_view<CharT, Traits>(str);。 |
(C++17 起) |
2) 行为如同一个 FormattedInputFunction。在构造并检查哨兵对象(其可能跳过前导空白字符)后,首先用 str.erase() 清空 str,然后从 is 读取字符并将其附加到 str,如同通过 str.append(1, c),直到以下条件之一变为真:
- 读取了
N
个字符,其中N
是 is.width(),如果 is.width() > 0,否则N
是 str.max_size(), - 流 is 中发生文件结束条件,或
- 对于 is 中的下一个字符 c,std::isspace(c, is.getloc()) 为 true(此空白字符保留在输入流中)。
如果没有提取任何字符,则在 is 上设置 std::ios::failbit,这可能抛出 std::ios_base::failure。
最后,调用 is.width(0) 以取消 std::setw(如果有)的效果。目录 |
[编辑] 异常
1) 如果在输出期间抛出异常,可能抛出 std::ios_base::failure。
[编辑] 参数
os | - | 字符输出流 |
is | - | 字符输入流 |
str | - | 要插入或提取的字符串 |
[编辑] 返回值
1) os
2) is
[编辑] 示例
运行此代码
#include <iostream> #include <sstream> #include <string> int main() { std::string greeting = "Hello, whirled!"; std::istringstream iss(greeting); std::string hello_comma, whirled, word; iss >> hello_comma; iss >> whirled; std::cout << greeting << '\n' << hello_comma << '\n' << whirled << '\n'; // Reset the stream iss.clear(); iss.seekg(0); while (iss >> word) std::cout << '+' << word << '\n'; }
输出
Hello, whirled! Hello, whirled! +Hello, +whirled!
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 25 | C++98 | n 是 os.width() 和 str.size() 中较小的一个 | n 是它们中较大的一个 |
LWG 90 | C++98 | 曾使用 std::isspace(c, getloc()) 检查 空格,但 getloc 未在 <string> 中声明 |
替换 getloc() 为 is.getloc() |
LWG 91 | C++98 | operator>> 未行为如同一个 FormattedInputFunction |
行为如同一个 FormattedInputFunction(格式化输入函数) |
LWG 211 | C++98 | 如果未提取任何字符,operator>> 未设置 failbit |
设置 failbit |
LWG 435 | C++98 | 字符通过 os.rdbuf()->sputn(str.data(), n) 插入, 且 LWG issue 25 的解决方案使得该行为 未定义,如果 os.width() 大于 str.size() |
首先确定填充 并插入带填充的 字符序列 |
LWG 586 | C++98 | operator<< 未行为如同一个 FormattedOutputFunction |
行为如同一个 FormattedOutputFunction(格式化输出函数) |
[编辑] 另请参阅
(C++17) |
对 string_view 执行流输出 (函数模板) |