Namespaces
Variants

operator<<,>> (std::basic_string)

From cppreference.net
std::basic_string
定义于头文件 <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) 表现为一个 格式化输出函数 。在构造并检查哨兵对象后, 确定输出格式的填充

随后将结果序列 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) 表现为 格式化输入函数 。构造并检查哨兵对象后(可能会跳过前导空白字符),首先通过 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
2) 若未从 is 提取任何字符(例如流处于文件末尾,或仅包含空白字符),或在输入期间抛出异常,则可能抛出 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';
    // 重置流状态
    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)
对字符串视图执行流输出操作
(函数模板)