Strange failure using stringstream to read float value

I have the following simple code that reads a float (double) value using C ++ stringstream. I use stringstream :: good to determine if a read is complete. Oddly enough, the value is read into the float variable, but good()returns false. The code below returns:

failed: 3.14159

I compiled the code using gcc 4.8.1 in mingw32, p g++ -std=c++11 test.cpp.

Any idea why this reading is not good? And what is the right way to say that the float really reads successfully?

thank

#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");
}
+4
source share
2 answers

, std::ios_base::eofbit , , . , good() true, .

, good() -. good() , ( eofbit) , , , -. eofbit , , - , .

, , . , !this->fail() , , good():

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

stringstream:: good()

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");
+1

Source: https://habr.com/ru/post/1540901/


All Articles