使用stringstream读取浮点值时出现奇怪的错误

strange failure using stringstream to read a float value

本文关键字:错误 读取 stringstream 使用      更新时间:2023-10-16

我有以下简单的代码,读取浮点值(双)使用c++ stringstream。我使用stringstream::good来检测读取是否成功。奇怪的是,该值被读入float变量,但good()返回false。底部的代码返回:

failed: 3.14159

我在mingw32下使用gcc 4.8.1编译代码,使用g++ -std=c++11 test.cpp

知道为什么这个读数不是good吗?怎样才能正确判断浮点数是否被成功读取呢?

感谢
#include <sstream>
#include <iostream>
using namespace std;
void readFloat(string s) {
  double i = 0!; 
  stringstream ss(s); 
  ss >> i;
  if (ss.good())
    cout << "read: " << i << endl;
  else
    cout << "failed: " << i << endl;
}
main() {
  readFloat("3.14159");
}

当流在提取过程中到达流的末尾时,他们将流状态中的std::ios_base::eofbit设置为提醒用户不能再读取字符。这意味着good()不再返回true,直到流状态被清除。

一般来说,good()不是确定I/O成功的可靠方法。good()作为条件意味着没有设置每个位(包括eofbit),如果您只是想确定I/O操作是否成功,这可能会产生误导。因为设置了eofbit,所以程序告诉您I/O操作失败了,而实际上没有。

相反,最好将整个提取包装在一个条件中,以确定它是否成功。在流中将隐式强制转换为布尔类型,并且流将在内部调用!this->fail(),这是比good()更好的选择:

if (ss >> i) {
    std::cout << "read: " << i << std::endl;
}
else {
    std::cout << "failed: " << i << std::endl;
}

这里没有奇怪的行为

stringstream::好()

如果到达文件的末尾,函数返回false。如果你在"ss>> i"之前测试良好,我相信它会返回true。

一个好的测试方法是:

  double i = 0.0;
  std::stringstream ss(s); 
  if (!ss.good())
    throw std::exception("Stream not good");
  ss >> i;
  if (!ss.eof())
    throw std::exception("Stream not read entirely");