我编写了一个应该写入文件的代码,但是当我执行该程序时,它显示“保存学生数据时出错”。这是代码。
#include<stdio.h>
typedef struct Student{
int numberOfStudents;
char name; // onoma foithth
char surname; // epi8eto foithth
};
int main(){
struct Student s1;
FILE *file=fopen("d:\\student.txt","w");
if(file==NULL){
printf("error in saving student data");
return 1;
}
while(1){
printf("Enter number of students: ");
scanf("%d",&s1.numberOfStudents);
printf("enter name: ");
scanf("%s",&s1.name);
printf("enter surname: ");
scanf("%s",&s1.surname);
fprintf(file,"%d\t%s\t%s\n",s1.numberOfStudents,s1.name,s1.surname);
printf("continue (Y/N)");
char ch=getch();
if (ch=='N' || ch=='n')
break;
}
fclose(file);
return 0;
}
我已经搜索过,但找不到问题所在。我的错误在哪里?
最佳答案
如果您想将 onoma foithth
存储在结构中,
name
字段应为 char array
,如图所示。将您的结构修改为
typedef struct Student{
int numberOfStudents;
char name[10]; // onoma foithth
char surname; // epi8eto foithth
};
然后在扫描name
时删除&
,因为name
本身就是地址。
scanf("%s",s1.name);
确保您在 fopen()
中给出了正确的路径
关于c - 使用结构写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239678/