Namespaces
Variants

std:: ws

From cppreference.net
< cpp ‎ | io ‎ | manip
定义于头文件 <istream>
template < class CharT, class Traits >
std:: basic_istream < CharT, Traits > & ws ( std:: basic_istream < CharT, Traits > & is ) ;

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

表现为一个 非格式化输入函数 ,但 is. gcount ( ) 不会被修改。在构造并检查哨兵对象后,从流中提取字符并丢弃它们,直到满足以下任一条件:

  • 输入序列中出现文件结束条件(此时函数会调用 setstate ( eofbit ) 但不会设置 failbit ;若在调用 ws is 已设置 eofbit ,则哨兵对象的构造会设置 failbit ,此情况除外)。
  • 输入序列中的下一个可用字符 c 不是由 std:: isspace ( c, is. getloc ( ) ) 确定的空白字符。该非空白字符不会被提取。

这是一个仅用于输入的I/O操纵器,可通过对任意类型为 std::basic_istream in 使用诸如 in >> std :: ws 的表达式来调用。

目录

参数

is - 输入流引用

返回值

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

注释

如果调用前流上已设置 eofbit ,哨兵对象的构造将设置 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++标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 415 C++98 调用 std::ws 可能不会构造哨兵对象
(与其他输入函数不一致)
要求构造哨兵对象

参见

提取并丢弃字符,直到找到指定字符
( std::basic_istream<CharT,Traits> 的公开成员函数)