Xeverous Xeverous - 11 months ago 52
C++ Question

std::stringstream operator>> fails to convert string to float

I can't understand why the second >> fails. Am I doing something wrong or missing some code?

std::ifstream file;
std::stringstream ss;
std::string str;
float f1, f2;

getline(file, str);
ss >> f1;

getline(file, str);//when packed inside if(), evalueates to true
ss >> f2; //when packed inside if(), evalueates to false - but why it fails?

std::cout<<"str = "<<str<<"\n";
std::cout<<"ss.str() = "<<ss.str()<<"\n";
std::cout<<"f1 = "<<f1<<"\nf2 = "<<f2<<"\n";




str = 0.120000
ss.str() = 0.120000
f1 = 0.12
f2 = 2.06831e+032

I have tried this code on multiple files and apparently only 1st insertion into float works, files have an empty line at the end


as Dan pointed, I tried extracting floats directly from file:

file >> f1;
file >> f2;

works ideally; also simplyfies code a lot

Answer Source

You have to add the following statement before the second attempt to read:


Why ?

Because when you've read the first line, the string stream contains "0.120000" and ss>>f1 will cause ss to reach the end of file. So that the eof flag is set.

When you reset the stringstreams's content with str(), you don't reset the state flags, so that the attempt to read will fail. adding the ss.clear() after you've reset the stringstreams's content will correct this situation.

Online demo