简体   繁体   中英

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;

file.open("file.txt");
getline(file, str);
ss.str(str);
ss >> f1;

getline(file, str);//when packed inside if(), evalueates to true
ss.str(str);
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";

file:

0.120000
0.120000

output:

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

Edit

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

file.open("file.txt");
file >> f1;
file >> f2;

works ideally; also simplyfies code a lot

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

ss.clear(); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM