c++ - strange failure using stringstream to read a float value -
i have following simple code reads float value (double) using c++ stringstream
. use stringstream::good detect whether read successful. strangely, value read float variable, good()
returns false. code @ bottom returns:
failed: 3.14159
i compiled code using gcc 4.8.1 under mingw32, g++ -std=c++11 test.cpp
.
any idea why read not good
? , what's proper way tell float read successfully?
thanks
#include <sstream> #include <iostream> using namespace std; void readfloat(string s) { double = 0!; stringstream ss(s); ss >> i; if (ss.good()) cout << "read: " << << endl; else cout << "failed: " << << endl; } main() { readfloat("3.14159"); }
when streams reach end of stream during extraction, set std::ios_base::eofbit
in stream state alert user no more characters can read. means good()
no longer returns true until stream state cleared.
generally, good()
not reliable way determine i/o success. good()
condition means every bit (including eofbit
) not set, can misleading if trying determine if i/o operation succeeded. because eofbit
set, program tell i/o operation failed when didn't.
instead, better wrap entire extraction in conditional determine if succeeds. there implicit cast in stream boolean , stream call !this->fail()
internally, better alternative good()
:
if (ss >> i) { std::cout << "read: " << << std::endl; } else { std::cout << "failed: " << << std::endl; }
Comments
Post a Comment