我要编写一个程序,该程序读入学生姓名和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
}
你能告诉我如何用EOF停止循环并正确读入名字和姓氏吗?感谢。
答案 0 :(得分:3)
用于检查EOF,您可以使用功能:
feof(FILE*) // if it returns 1 then it is EOF reached.
您可以像下面的代码段一样使用它:
if (feof(fp) == 1)
break;
和第二个问题:
printf("Enter last name of student %d: ",i+1);
fgets(firstName[i],21,stdin); // this is incorrect.
使用'lastname'而不是'firstname'。它应该是这样的:
fgets(lastName[i],21,stdin);
这样你就会覆盖名字的值