简体   繁体   English

std :: stringstream operator >>无法将字符串转换为float

[英]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 我已经在多个文件上尝试了这个代码,显然只有第一次插入到float中,文件末尾有一个空行

Edit 编辑

as Dan pointed, I tried extracting floats directly from file: 正如Dan指出的那样,我尝试直接从文件中提取浮点数:

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. 因为当您读取第一行时,字符串流包含"0.120000"ss>>f1将导致ss到达文件末尾。 So that the eof flag is set. 这样就设置了eof标志。

When you reset the stringstreams's content with str() , you don't reset the state flags, so that the attempt to read will fail. 使用str()重置stringstreams的内容时,不会重置状态标志,因此尝试读取将失败。 adding the ss.clear() after you've reset the stringstreams's content will correct this situation. 在重置stringstreams的内容后添加ss.clear()将纠正这种情况。

Online demo 在线演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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