我不明白为什么第二个 >> 无法成功。是我做错了什么还是缺少了某些代码?
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
我曾经在多个文件上尝试过这段代码,显然只有第一次插入浮点数有效,文件末尾有一个空行。
编辑
正如丹所指出的,我尝试直接从文件中提取浮点数:
file.open("file.txt");
file >> f1;
file >> f2;
工作得很理想;也大大简化了代码
stringstream
,直接在ifstream
上使用流operator>>
。 - Dan