Incorrect data input with fstream

痞子三分冷 提交于 2019-12-12 01:14:15

问题


I tried to read in data from a text file using fstream but got wrong data.

ifstream fin ("C:\\Users\\rEgonicS\\Documents\\test.in");
int number;
fin >> number;
cout << number;

test.in is simply 12.
cout reads 4273190.
Can someone explain why this is so and how to fix it?


回答1:


The most likely cause is that the file open failed. Check the status after opening, and also after reading; for a simple test, do something like this:

ifstream fin ("C:\\Users\\rEgonicS\\Documents\\test.in");
if (!fin) cout << "File open failed\n";
int number;
fin >> number;
if (!fin) cout << "File read failed\n";
cout << number;

This might give a further clue as to what's going on.



来源:https://stackoverflow.com/questions/3095339/incorrect-data-input-with-fstream

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