#include<stdio.h> #include<string.h> #include<stdlib.h> struct student{ char number[10]; char name[15]; double cscore; double mathscore; double englishscore; double sum; struct student *next; }; void tianjiaxinxi() { int n; FILE *fp; if((fp=fopen("data.txt","w"))==NULL) { printf("File open error!\n") ; exit(0); } printf("请选择添加几名学生的信息:\n");scanf("%d",n); getchar(); struct student u[n]; for(int i=0;i<n;i++) { printf("请输入学生信息:\n"); scanf("%s%s%lf%lf%lf",u[i].number,u[i].name,&u[i].cscore,&u[i].mathscore,&u[i].englishscore); u[i].sum=u[i].cscore+u[i].englishscore+u[i].mathscore; fprintf(fp,"%s %s %.2f %.2f %.2f %.2f", u[i].number,u[i].number,u[i].name,u[i].cscore,u[i].mathscore,u[i].englishscore); } if(fclose(fp)) { printf("Can not close the file!\n"); exit(0); } } int main() { tianjiaxinxi(); return 0; }为什么执行完给n赋值后,按回车就结束程序了
时间: 2024-03-04 22:48:46 浏览: 57
C标准库函数集
5星 · 资源好评率100%
在代码中,scanf的语句`scanf("%d",n);`应该改为`scanf("%d",&n);`,因为scanf需要传入参数的地址,而不是参数本身。所以导致程序在scanf语句处出现了错误。修改后的代码如下:
```c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student{
char number[10];
char name[15];
double cscore;
double mathscore;
double englishscore;
double sum;
struct student *next;
};
void tianjiaxinxi() {
int n;
FILE *fp;
if((fp=fopen("data.txt","w"))==NULL) {
printf("File open error!\n") ;
exit(0);
}
printf("请选择添加几名学生的信息:\n");
scanf("%d",&n); //修改这里
getchar();
struct student u[n];
for(int i=0;i<n;i++) {
printf("请输入学生信息:\n");
scanf("%s%s%lf%lf%lf",u[i].number,u[i].name,&u[i].cscore,&u[i].mathscore,&u[i].englishscore);
u[i].sum=u[i].cscore+u[i].englishscore+u[i].mathscore;
fprintf(fp,"%s %s %.2f %.2f %.2f %.2f", u[i].number,u[i].name,u[i].cscore,u[i].mathscore,u[i].englishscore,u[i].sum);
}
if(fclose(fp)) {
printf("Can not close the file!\n");
exit(0);
}
}
int main() {
tianjiaxinxi();
return 0;
}
```
这样修改后,程序就可以正常运行了。
阅读全文