文件输出小问题
#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,输出结果就正确了,你可以去试一下。
[解决办法]
[解决办法]
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
whlie (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
whlie (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。