关于文件的读与写
#include<iostream>#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream infile("e:\\exams.dat",ios::in);
ofstream outfile("e:\\score.dat",ios::trunc);
char key[20],answer[5][30];
int flag[5]={1,1,1,1,1},score[5];
int i,j,len,s;
string id[5];
if (!infile) { cerr<<"INFILE Open error"<<endl; exit(1); }
if (!outfile) { cerr<<"OUTFILE open error"<<endl; exit(1); }
infile.getline(key,21); //21
for (i=0;i<5;i++) //取值
{
infile>>id[i];
infile>>answer[i];
}
for (i=0;i<5;i++) //判断是否20个,统计分数,是否有效
{
len=0;
s=0;
len=strlen(answer[i]);
if(len<20) flag[i]=0;
if(len>20) flag[i]=2;
for (j=0;j<20;j++) if(answer[i][j]==key[j]) s++;
score[i]=s;
for(j=0;j<20;j++)
{
if(answer[i][j]>'f'||answer[i][j]<'a')
{
flag[i]=3;
break;
}
}
}
cout<<"The scores are listed as follows"<<endl;
for (i=0;i<5;i++) //终端输出
{
if (flag[i]==1) cout<<id[i]<<" "<<score[i]<<endl;
if (flag[i]==0) cout<<id[i]<<" "<<"Too few answers"<<endl;
if (flag[i]==2) cout<<id[i]<<" "<<"Too many answers"<<endl;
if (flag[i]==3) cout<<id[i]<<" "<<"Invalid answers"<<endl;
}
outfile<<"The scores are listed as follows"<<endl;
for (i=0;i<5;i++) //文件输出
{
if (flag[i]==1) outfile<<id[i]<<" "<<score[i]<<endl;
if (flag[i]==0) outfile<<id[i]<<" "<<"Too few answers"<<endl;
if (flag[i]==2) outfile<<id[i]<<" "<<"Too many answers"<<endl;
if (flag[i]==3) outfile<<id[i]<<" "<<"Invalid answers"<<endl;
}
outfile.close();
infile.close();
return 0;
}
其中
exam.dat文件是
abcdefabcdefabcdefab
1234567 abcdefabcdefabcdefab
9876543 abddefbbbdefcbcdefac
5554446 abcdefabcdefabcdef
4445556 abcdefabcdefabcdefabcd
3332221 abcdefghijklmnopqrst
问题是我无法输出到文件中,这是怎么回事
求指导