命名空间
变体
操作

std::ws

来自 cppreference.cn
< cpp‎ | io‎ | manip
 
 
 
输入/输出操纵符
浮点格式化
整数格式化
布尔格式化
字段宽度和填充控制
其他格式化
空白符处理
ws
输出刷新
(C++20)  

状态标志操作
时间和货币 I/O
(C++11)
(C++11)
(C++11)
(C++11)
带引号的操纵符
(C++14)
 
定义于头文件 <istream>
template< class CharT, class Traits >
std::basic_istream<CharT, Traits>& ws( std::basic_istream<CharT, Traits>& is );

从输入流中丢弃前导空白符。

行为类似于 UnformattedInputFunction,但 is.gcount() 不会被修改。在构造并检查 sentry 对象后,从流中提取字符并丢弃它们,直到发生以下任一情况

  • 输入序列中出现文件结束条件(在这种情况下,函数调用 setstate(eofbit) 但不设置 failbit;如果 eofbit 在调用 ws 之前已在 is 上设置,则不适用,在这种情况下,sentry 对象的构造将设置 failbit)。
  • 输入序列中的下一个可用字符 c 不是空白符,由 std::isspace(c, is.getloc()) 确定。非空白字符不会被提取。

这是一个仅用于输入的 I/O 操纵符,可以像这样调用它 in >> std::ws 对于任何 in 类型为 std::basic_istream

目录

[编辑] 参数

is - 输入流的引用

[编辑] 返回值

is(提取连续空白符后的流的引用)。

[编辑] 注意

如果在调用之前流上设置了 eofbit,则 sentry 对象的构造将设置 failbit

[编辑] 示例

#include <iomanip>
#include <iostream>
#include <istream>
#include <sstream>
#include <string>
 
int main()
{
    for (const char* str : {"     #1 test", "\t #2 test", "#3 test"})
    {
        std::string line;
        std::getline(std::istringstream{str}, line);
        std::cout << "getline returns:\t" << std::quoted(line) << '\n';
 
        std::istringstream iss{str};
        std::getline(iss >> std::ws, line);
        std::cout << "ws + getline returns:\t" << std::quoted(line) << '\n';
    }
}

输出

getline returns:	"     #1 test"
ws + getline returns:	"#1 test"
getline returns:	"	 #2 test"
ws + getline returns:	"#2 test"
getline returns:	"#3 test"
ws + getline returns:	"#3 test"

[编辑] 缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
LWG 415 C++98 调用 std::ws 可能不会构造 sentry
对象(与其他输入函数不一致)
需要构造
sentry 对象

[编辑] 参见

提取并丢弃字符,直到找到给定字符
(std::basic_istream<CharT,Traits> 的公共成员函数) [编辑]