问题描述
我不明白为什么第二个 >> 失败了.是我做错了什么还是遗漏了一些代码?
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";
文件:
0.120000
0.120000
输出:
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.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();
为什么?
因为当您阅读第一行时,字符串流包含 "0.120000"
并且 ss>>f1
将导致 ss
到达文件末尾.以便设置 eof 标志.
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.
当您使用 str()
重置 stringstreams 的内容时,您不会重置状态标志,因此读取尝试将失败.在重置 stringstreams 的内容后添加 ss.clear() 将纠正这种情况.
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.
这篇关于std::stringstream 运算符>>无法将字符串转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!