阅读列表

时间:2016-11-28 11:50:09

标签: c loops scanf fgets eof

我要编写一个程序,该程序读入学生姓名和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
}
  1. 如果学生达到200或者用户输入EOF,则必须停止读取数值。
  2. 学生的名字或姓氏可能包含多个部分(类似于“约翰约翰”)所以我使用fgets而不是scanf和%s来读取空格之后的单词,但它失败了,只有姓氏是存储
  3. 你能告诉我如何用EOF停止循环并正确读入名字和姓氏吗?感谢。

1 个答案:

答案 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);

这样你就会覆盖名字的值