std::ws
来自cppreference.com
| 在标头 <istream> 定义
|
||
| |
||
从输入流舍弃前导空白符。
表现为无格式输入函数 (UnformattedInputFunction) ,但不修改 is.gcount()。在构造并检查 sentry 对象后,从流提取并舍弃字符,直到出现下列任一条件:
- 输入序列中出现文件尾条件(此时函数会调用
setstate(eofbit)但不会设置failbit;如果调用ws前已在is上设置eofbit,那么不适用这条,此时 sentry 对象的构造会设置failbit)。
- 输入序列中下个可用字符
c不是以std::isspace(c, is.getloc())确定的空白字符。不会提取该非空白字符。
这是只输入的输入/输出操纵符,可用类似 in >> std::ws 的表达式对任何 std::basic_istream 类型的 in 调用。
参数
| 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 返回:\t\t" << quoted(line) << '\n';
std::istringstream iss{str};
std::getline(iss >> std::ws, line);
std::cout << "ws + getline 返回:\t" << quoted(line) << '\n';
}
}
输出:
getline 返回: " #1 test"
ws + getline 返回: "#1 test"
getline 返回: " #2 test"
ws + getline 返回: "#2 test"
getline 返回: "#3 test"
ws + getline 返回: "#3 test"
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 415 | C++98 | 调用 std::ws 不一定会构造 sentry 对象(与其他输入函数不一致)
|
需要构造 sentry 对象 |
参阅
| 持续提取并丢弃字符,直到找到给定字符 ( std::basic_istream<CharT,Traits> 的公开成员函数) |