gpt4 book ai didi

c++ - 为什么 complex 上的 operator>> 在到达 EOF 时不设置 eofbit?

转载 作者:可可西里 更新时间:2023-11-01 16:47:24 25 4
gpt4 key购买 nike

我正在尝试阅读尽可能多的 std::complex<double>尽可能从文件(或任何 std::istream )。如果操作失败,我会检查 ios::eof()。如果没有设置,我就假设解析数据有错误,我可以向用户报告输入文件有错误。这个方案适用于 double ,但不知何故它在复数上失败了。为什么?

这里是重现问题的一些代码:

std::istringstream istr("4 1.2");
std::complex<double> val;

while( istr >> val )
std::cout << " val = " << val << std::endl;

std::cout << "flags: eof=" << istr.eof() << " fail=" << istr.fail() << " bad=" << istr.bad() << std::endl;

输出是

 val = (4,0)
val = (1.2,0)
flags: eof=0 fail=1 bad=0

如果我替换 std::complex<double>double ,它按预期工作,屈服

 val = 4
val = 1.2
flags: eof=1 fail=1 bad=0

此问题出现在 libstdc++ 中,但它似乎适用于 libc++:

run on coliru with g++

run on coliru with clang++ and libc++

编辑 我找到了一个 bug report从 2013 年开始,但问题似乎仍然存在,而且图书馆很常见。有没有一种方法可以使它对任何人都适用,而无需编写我自己的解析器?

最佳答案

它源于标准的措辞:

[complex.ops]
12 Effects: Extracts a complex number x of the form: u, (u), or (u,v), where u is the real part and v is the imaginary part (27.7.2.2).
13 Requires: The input values shall be convertible to T. If bad input is encountered, calls is.setstate(ios_base::failbit) (which may throw ios::failure (27.5.5.4)).
14 Returns: is.
15 Remarks: This extraction is performed as a series of simpler extractions. Therefore, the skipping of whitespace is specified to be the same for each of the simpler extractions.

特别是它没有指定在任何情况下都应该设置 eofbit。甚至评论也没有指定执行什么操作以及它们的语义是什么。有一个Defect Report关于它,它通过指定操作的语义来建议解决方案,如果幸运的话,它将进入 C++17。

关于c++ - 为什么 complex<double> 上的 operator>> 在到达 EOF 时不设置 eofbit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37859657/

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