求各位大神帮帮小弟!c语言程序!

2024-12-03 14:59:17
推荐回答(1个)
回答(1):

#include
typedef struct
{
char no[10];
char name[10];
double foreign;
double spec1;
double spec2;
double total;
} StudentType;

void WriteToFile();
void ReadFromFile();

int main()
{
int select;
do
{
printf("1.录入成绩 2.输出成绩 0.退出\n");
printf("请输入要执行的操作:");
scanf("%d",&select);
switch (select)
{
case 1: WriteToFile(); break;
case 2: ReadFromFile(); break;
default: printf("退出程序!"); break;
}
} while ((select==1||select==2));
return 0;
}
void WriteToFile()
{
FILE *fp=NULL;
StudentType stu;
char flag='y';
fp=fopen("student.txt","a");
if (fp==NULL)
{
printf("文件打开失败!\n");
// return -1;/*这是因为返回*/定义void类型函数不能返回实值。把这句去掉,就OK。
}
while((flag=='y'||flag=='Y'))
{
printf("请输入考生考号:");
scanf("%s",stu.no);
printf("请输入考生姓名:");
scanf("%s",stu.name);
printf("请输入考生外语成绩:");
scanf("%lf",&stu.foreign);
printf("请输入考生专业课1的成绩:");
scanf("%lf",&stu.spec1);
printf("请输入考生专业课2的成绩:");
scanf("%lf",&stu.spec2);
stu.total=stu.foreign+stu.spec1+stu.spec2;
fprintf(fp,"%10s%10s%8.2f ",stu.no,stu.name,stu.foreign);
fprintf(fp,"%8.2s%8.2s%8.2f",stu.spec1,stu.spec2,stu.total);
fputc('\n',fp);
fflush(stdin);
printf("继续输入吗?继续请按y或Y:");
scanf("%c",&flag);
}
fclose(fp);
return;
}
void ReadFromFile()
{
FILE *fp=NULL;
StudentType stu;
fp=fopen("student.txt","r");
if (fp==NULL)
{
printf("文件打开失败!");
//return -1;/*同上*/
}
printf(" 考生姓名 总分\n");
while (!feof(fp))
{
fscanf(fp,"%s%s",stu.no,stu.name);
fscanf(fp,"%lf%lf%lf%lf",&stu.foreign,&stu.spec1,&stu.spec2,&stu.total);
printf("%10s%8.2f\n",stu.name,stu.total);
}
fclose(fp);
return;
}
已指出错误,可正确运行,忘采纳。。。