【发布时间】:2016-11-28 11:50:08
【问题描述】:
我必须编写一个程序,该程序读取学生姓名和 ID 列表,并根据名字、姓氏和 ID 对它们进行排序。但是我的代码目前有两个问题。
#include <stdio.h>
int main() {
char firstName[200][21], lastName[200][51];
unsigned short id[200]; // used short to decrease memory usage
int i;
for (i=0; i<200; ++i) {
printf("Enter first name of student %d: ",i+1);
getchar(); // FIX to consume enter
fgets(firstName[i],21,stdin);
printf("Enter last name of student %d: ",i+1);
fgets(firstName[i],21,stdin);
printf("Enter student number of student %d: ",i+1);
scanf("%hu",&id[i]);
printf("You've entered %s %s with ID %hu",firstName[i],lastName[i],id[i]);
}
// other functions to do after reading in the data is successfully done
}
- 如果学生人数达到 200 或用户输入 EOF,则必须停止读取值。
- 学生的名字或姓氏可能由多个部分组成(例如“john john”,所以我使用 fgets 而不是 scanf 和 %s 来读取空格之后的单词,但它失败并且只有姓氏是已存储。
您能告诉我如何使用 EOF 停止循环并正确读取名字和姓氏吗?谢谢。
【问题讨论】: