C语言 从键盘输入10个整数存放在数组a中,并将数组a中的数据“写”到“f1.txt”文件中,为什么出错?

这是我写的程序,为什么输入完数据后就出错?!
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE * fp ;
if ( (fp = fopen("f1.txt","r")) == NULL )
{
printf ( "cannot open this file\n" ) ;
exit (0) ;
}
int a[10] = {0} ;
for ( int i = 0 ; i < 10 ; i ++ )
{
scanf ( "%d" , &a[i] ) ;
}
for ( i = 0 ; i < 10 ; i ++ )
{
fprintf ( fp , "%5.d" , a[i] ) ;
}
fclose(fp) ;
int b[10] = {0} , sum = 0 ;
fp = fopen ("f1" , "r+") ;
for ( i = 0 ; i < 10 ; i ++ )
{
fread ( &b[i] , 4 , 1 , fp ) ;
}
fclose (fp) ;
for ( i = 0 ; i < 10 ; i ++ )
{
sum += b[i] ;
printf ( "%d " , b[i] ) ;
}
printf ( "\nsum=%d\n" , sum ) ;
}

#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
struct student
{
int id;
char name[20];
char sex[4];
unsigned long birthday;
float height;
float weight;
};
int main()
{

ifstream fin("1.txt");
if(!fin)
{
cout<<"文件打开失败\n";
return 0;
}
cout<<setiosflags(ios::fixed)<<setprecision(1)
<<setiosflags(ios::left);
cout<<setw(10)<<"学号"
<<setw(20)<<"姓名"
<<setw(5)<<"性别"
<<setw(10)<<"生日"
<<setw(20)<<"身高"
<<setw(20)<<"体重"
<<endl;
student S;
while(fin>>S.id>>S.name>>S.sex>>S.birthday>>S.height>>S.weight)
{
cout<<setw(10)<<S.id
<<setw(20)<<S.name
<<setw(5)<<S.sex
<<setw(10)<<S.birthday
<<setw(20)<<S.height
<<setw(20)<<S.weight
<<endl;
}
fin.close();
return 0;
}
#include<iostream>
#include<fstream>
using namespace std;
struct student
{
int id;
char name[20];
char sex[2];
unsigned long birthday;
float height;
float weight;
};
student room[4];
int main()
{
int i=0;
for(i=0;i<4;i++)
{
cout<<"学号";
cin>>room[i].id;
cout<<"名字:"<<endl;
cin>>room[i].name;
cout<<"性别:";
cin>>room[i].sex;
cout<<"生日:";
cin>>room[i].birthday;
cout<<"身高"<<endl;
cin>>room[i].height;
cout<<"体重"<<endl;
cin>>room[i].weight;
}
ofstream fout("1.txt");
if(!fout)
{
cout<<"文件打开失败\n";
return 0;
}
//fout<<"学号 "<<"名字 "<<"性别 "<<"生日 "<<"身高"<<"体重"<<endl;
for(i=0;i<4;i++)
{
fout<<room[i].id<<" "
<<room[i].name<<" "
<<room[i].sex<<" "
<<room[i].birthday<<" "
<<room[i].height<<" "
<<room[i].weight<<endl;
}
fout.close();
return 0;
}

你参考这个再试试
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-07-08
第一次写入文件时,用"w",可写入~
第2个回答  2011-07-04
fp = fopen ("f1" , "r+") ;
文件名写错了
fp = fopen ("f1.txt" , "r+") ;本回答被提问者和网友采纳
相似回答