operator<<,>>(std::basic_string)
来自cppreference.com
| 在标头 <string> 定义
|
||
template< class CharT, class Traits, class Allocator > std::basic_ostream<CharT, Traits>& operator<<( std::basic_ostream<CharT, Traits>& os, const std::basic_string<CharT, Traits, Allocator>& str ); |
(1) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& operator>>( std::basic_istream<CharT, Traits>& is, std::basic_string<CharT, Traits, Allocator>& str ); |
(2) | |
1) 表现为有格式输出函数 (FormattedOutputFunction) 。构造并检查哨兵对象后,确定输出格式填充。
然后将结果序列的每个字符(str 的内容加上填充)插入到输出流 os,如同通过调用 os.rdbuf()->sputn(seq, n),其中 n 是 std::max(os.width(), str.size())。
最后,调用 os.width(0) 以取消 std::setw 的效果,如果存在。
|
等价于 |
(C++17 起) |
2) 表现为有格式输入函数 (FormattedInputFunction) 。构造并检查哨兵对象,这可能会跳过前导空白符,然后首先以
str.erase() 清除 str,再从 is 读取字符并后附它们到 str,如同用 str.append(1, c),直到满足下列任一条件:
- 读取了
N个字符,其中如果is.width() > 0,那么N是is.width(),否则N是str.max_size(), - 流
is中出现文件尾条件,或者 std::isspace(c, is.getloc())对is中的下个字符c是true(空白符留在输入流中)。
如果没有提取任何字符,那么设置 is 上的 std::ios::failbit,这可能会抛出 std::ios_base::failure。
is.width(0) 以取消 std::setw 的效果,如果存在。 异常
1) 如果在输出中抛出异常,那么可能会抛出 std::ios_base::failure。
2) 如果没有从
is 中提取任何字符(例如流在文件尾或仅有空白符组成),或在输入中抛出异常,那么可能会抛出 std::ios_base::failure。参数
| os | - | 字符输出流 |
| is | - | 字符输入流 |
| str | - | 插入或提取的字符串 |
返回值
1)
os2)
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';
// 重置流
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()) 被用来检查空白字符,但 <string> 中没有声明 getloc
|
将 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 问题 25 的解决方案导致 os.width() 大于 str.size() 时的行为未定义
|
先确定填充,并改成 插入填充后的字符序列 |
| LWG 586 | C++98 | operator<< 没有表现为有格式输出函数 (FormattedOutputFunction) |
表现为 有格式输出函数 (FormattedOutputFunction) |
参阅
(C++17) |
进行字符串视图的流输出 (函数模板) |