![](/img/trans.png)
[英]Custom Stringstream - Convert std::wstring & std::string
[英]std::stringstream operator>> fails to convert string to float
我無法理解為什么第二個>>失敗。 我做錯了什么或遺漏了一些代碼?
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
我已經在多個文件上嘗試了這個代碼,顯然只有第一次插入到float中,文件末尾有一個空行
編輯
正如Dan指出的那樣,我嘗試直接從文件中提取浮點數:
file.open("file.txt");
file >> f1;
file >> f2;
理想的工作; 也簡化了很多代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.