operator<<,>> (std::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) | |
随后将结果序列 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 起) |
-
读取了
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 的效果(如果存在)。
目录 |
异常
参数
| os | - | 字符输出流 |
| is | - | 字符输入流 |
| str | - | 待插入或提取的字符串 |
返回值
示例
#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
(
)
)
检查空格,
但
getloc
未在
<string>
中声明
|
将
getloc
(
)
替换为 is. getloc ( ) |
| LWG 91 | C++98 |
operator>>
未表现为
格式化输入函数 |
表现为
格式化输入函数 |
| 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<<
未表现为
格式化输出函数 |
表现为
格式化输出函数 |
参见
|
(C++17)
|
对字符串视图执行流输出操作
(函数模板) |