为了账号安全,请及时绑定邮箱和手机立即绑定

这几行代码为什么不能运行出来?

这几行代码为什么不能运行出来?

C
sunny超1 2017-10-21 17:19:49
#include<stdio.h>#define SIZE 5struct student{ long num; char name[10]; int score[3];}stu[SIZE];void save(){ FILE *fp; int i; if((fp=fopen("C:\\stud.txt","w"))==NULL) {  printf("cannot open file\n");  return;} for(i=0;i<SIZE;i++)  if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1)   printf("file write error\n");  fclose(fp);}main(){ int i; for(i=0;i<SIZE;i++)   scanf("%ld%s%d%d%d",&stu[i].num,stu[i].name,&stu[i].score[0],&stu[i].score[1],&stu[i].score[2]);  save();}
查看完整描述

2 回答

?
噗_嗤

TA贡献1条经验 获得超0个赞

不知道题主用的是什么,我这边用VS和VC都能跑,只是有个warn,这在main()之前加个int就可以解决。我猜测是路径问题,修改一下这一句。

 if((fp=fopen("C:\\stud.txt","w"))==NULL)

                     

查看完整回答
反对 回复 2017-10-22
  • sunny超1
    sunny超1
    感谢你的回答,冒昧问您一句,是不是换成类似于这样 if((fp=fopen("D:\\stud.txt","w"))==NULL)这种?还有就是这几行运行完后出来得命令提示符,输入其中的数据,生成的名为stud的TXT文件是乱码的,又是哪里有问题呢?期待你的再次回复。
  • 噗_嗤
    噗_嗤
    可能我没有写清楚,我的意思是这个路径下有你建立的那个stud.txt文件就行。 还有那个乱码是因为字幕编码问题。 fwrite()这个函数是以二进制写入的,如果你使用fread()再读出来其实不是乱码,而文本只能显示一部分,所以看起来是乱码。 如果把fwrite()改成fprintf()就可以,比如改成 fprintf(fp,"%ld%s%d%d%d\n", stu[i].num, stu[i].name, stu[i].score[0], stu[i].score[1], stu[i].score[2]);
  • sunny超1
    sunny超1
    恩恩,我立即按照你的方法试了下,可有一个error和一个warning。 #include<stdio.h> #define SIZE 5 struct student{ long num; char name[10]; int score[3]; }stu[SIZE]; void save(){ FILE *fp; int i; if((fp=fopen("C:\\stud.txt","w"))==NULL) { printf("cannot open file\n"); return; } for(i=0;i<SIZE;i++) if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1) printf("file write error\n"); fclose(fp); } int main(){ int i; for(i=0;i<SIZE;i++) fprintf(fp,"%ld%s%d%d%d\n",stu[i].num,stu[i].name,stu[i].score[0],stu[i].score[1],stu[i].score[2]); save(); }
点击展开后面1
  • 2 回答
  • 0 关注
  • 1185 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信