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

自古美人都是妖i 提交于 2019-12-12 16:47:21

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/39052538/stdstringstream-operator-fails-to-convert-string-to-float

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!