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 。在构造和检查 sentry 对象后, 确定输出格式填充。
然后将结果序列 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); 。 |
(since C++17) |
2) 行为如同 FormattedInputFunction 。在构造和检查 sentry 对象后(可能跳过前导空白符),首先用 str.erase() 清空 str ,然后从 is 读取字符并将它们追加到 str ,如同 str.append(1, c) ,直到以下条件之一为真
- 读取
N
个字符,其中如果 is.width() > 0 则N
为 is.width() ,否则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++ 标准。
DR | 应用于 | 发布时的行为 | 正确行为 |
---|---|---|---|
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) |
对字符串视图执行流输出 (函数模板) |