strange failure using stringstream to read a float value

c++, c++11, stringstream

Solution

When streams reach the end of the stream during an extraction, they set the `std::ios_base::eofbit` in the stream state to alert to the user that no more characters can be read. This means that `good()` no longer returns true until the stream state is cleared.

Generally, `good()` is not a reliable way to determine I/O success. `good()` as a condition means that every bit (including `eofbit`) is not set, which can be misleading if you are simply trying to determine if an I/O operation succeeded. Because `eofbit` is set, your program tell you that your I/O operation failed when it didn't.

Instead, it is better to wrap the entire extraction in a conditional to determine if it succeeds. There will be an implicit cast in the stream to boolean and the stream will call `!this->fail()` internally, which is a better alternative than `good()`:

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

Problem

I have the following simple code which reads a float value (double) using c++ `stringstream`. I use stringstream::good to detect whether the read is successful. Strangely, the value is read into the float variable, but `good()` returns false. The code at the bottom returns: ``` failed: 3.14159 ``` I compiled the code using gcc 4.8.1 under mingw32, with `g++ -std=c++11 test.cpp`. Any idea why this read is not `good`? And what's the proper way to tell that the float is actually read successfully? Thanks ``` #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"); } ```

Original source