gpt4 book ai didi

c++ - EOF 上的 std::ws 行为

转载 作者:行者123 更新时间:2023-12-01 14:29:05 24 4
gpt4 key购买 nike

我偶然发现了不同编译器之间的行为差​​异。假设如下代码:

#include <sstream>
#include <iostream>

using namespace std;

int main() {
istringstream ss("100");
int val;
ss >> val;
cout << "fail: " << ss.fail() << " eof: " << ss.eof() << endl;
ss >> std::ws;
cout << "fail: " << ss.fail() << " eof: " << ss.eof() << endl;
}

VS2019 和 Clang 10 使用 libc++ 生成的输出是:

fail: 0 eof: 1
fail: 1 eof: 1

虽然 VS2015 和带有 libstdc++ 的 GCC 10.2 生成:

fail: 0 eof: 1
fail: 0 eof: 1

那么问题是哪种实现是正确的?当 eofbit 已经设置时,std::ws 是否应该设置 failbit?

我在标准中查找了 std::ws,它说:

30.7.4.4 Standard basic_istream manipulators [istream.manip]

template<class charT, class traits> basic_istream<charT, traits>&ws(basic_istream<charT, traits>& is);

Effects: Behaves as an unformatted input function (30.7.4.3), exceptthat it does not count the number of characters extracted and does notaffect the value returned by subsequent calls to is.gcount(). Afterconstructing a sentry object extracts characters as long as the nextavailable character c is whitespace or until there are no morecharacters in the sequence. Whitespace characters are distinguishedwith the same criterion as used by sentry::sentry (30.7.4.1.3). If wsstops extracting characters because there are no more available itsets eofbit, but not failbit.

所以最后明确说明它设置eofbit,但在没有可用字符时不设置failbit。但随后它也表现为一个未格式化的输入函数,它创建一个 sentry 对象。当 is.good() 为 false 时,sentry 构造函数将调用 is.setstate(failbit)。所以在某种程度上,这两种实现都不是完全错误的。更了解标准语的人能否阐明哪种行为是正确的以及我应该在哪里提交错误?

最佳答案

failbit应该设置。由 sentry 完成对象,什么 ws构造第一件事。

[istream::sentry]/2
explicit sentry(basic_istream<charT, traits>& is, bool noskipws = false);
Effects: If is.good() is false, calls is.setstate(failbit). Otherwise, ...

关于c++ - EOF 上的 std::ws 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63299651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com