文件输出小问题
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fop("data.txt");
cout<<"请输入学生姓名学号和录取成绩:"<<endl;
string name,studentId,score;
while (cin>>name>>studentId>>score)
{
fop<<name<<" "<<studentId<<" "<<score<<endl;
}
cin.clear();
fop.close();
ifstream fip("data.txt");
if (!fip)
{
cout<<"Can't open the file."<<endl;
}
while (!fip.eof())
{
fip>>name>>studentId>>score;
cout<<name<<" "<<studentId<<" "<<score<<endl;
}
fip.close();
return 0;
}
输入 a 001 666
b 002 777
输出 a 001 666
b 002 777
b 002 777
怎么 b 002 777输出2次呢?
[解决办法]
我遇到过这个问题 看我这里 虽然我是用的C你用的C++ 但原理是一样的
http://blog.csdn.net/shimachao/article/details/7096832
[解决办法]
while (cin>>name>>studentId>>score)
{
fop<<name<<" "<<studentId<<" "<<score<<endl;
}
这不是死循环吗?呵呵,这不是重点。
我用运行了下你的代码,就那你的输入来说。第一次直接运行,和你的结果一样,我打开data.txt文件来看,就知道原因了,因为你输入完姓名学号和录取成绩后,都输出了一个endl,最后一次也不例外,所以在文件的最后不是777,在777之后还有一个endl,所以循环判断条件!fip.eof()为假。
我修改了一下,就是最后一次写入文件,写入endl,输出结果就正确了,你可以去试一下。
[解决办法]