文件操作--文本文件读入
时间: 1ms 内存:128M
描述:
现有100名学生的姓名(name)、学号(num)、英语(English)、数学(Math)、语文(Chinese)成绩存储在一个文本文件student.dic中(姓名不超过20个字符,学号和各科成绩为整型,各数据之间用空格分隔),现要求将指定行数的学生信息输出,每条信息占一行。
前5行学生信息为:
akdh 13773 84 83 66
fjka 30257 15 14 88
sfhklas 61281 87 8 31
hfu 38635 55 50 60
iwehfk 92803 54 6 77
输入:
要输出行号的整数序列,以0作为结束标志。
输出:
输出学生信息,每个学生占一行
示例输入:
1 3 5 0
示例输出:
akdh 13773 84 83 66
sfhklas 61281 87 8 31
iwehfk 92803 54 6 77
提示:
参考答案(内存最优[1088]):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student
{
char name[20];
int num;
int eng;
int math;
int chi;
}stu[100];
int main()
{
FILE *fp;
struct student stu[100];
if((fp=fopen("student.dic","r"))==NULL)
{
printf("Cannot open\n");
exit(1);
}
int i=0;
for(i=0;i<100;i++)
{
fscanf(fp,"%s %d %d %d %d",&stu[i].name,&stu[i].num,&stu[i].eng,&stu[i].math,&stu[i].chi);
}
fclose(fp);
int n;
scanf("%d",&n);
while(n!=0)
{
printf("%s %d %d %d %d\n",stu[n-1].name,stu[n-1].num,stu[n-1].eng,stu[n-1].math,stu[n-1].chi);
scanf("%d",&n);
}
return 0;
}
参考答案(时间最优[0]):
#include<stdio.h>
int main()
{
char c[105][20]={'\0'};
int a[105]={0},b[105]={0},d[105]={0},e[105]={0},i;
FILE *fin;
fin=fopen("student.dic","r");
for(i=1;~fscanf(fin,"%s%d%d%d%d",c[i],a+i,b+i,d+i,e+i); i++);
while(scanf("%d",&i)&&i)
printf("%s %d %d %d %d\n",c[i],a[i],*(b+i),*(d+i),*(e+i));
fclose(fin);
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。