【问题标题】:Reading in a list在列表中阅读
【发布时间】: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
}
  1. 如果学生人数达到 200 或用户输入 EOF,则必须停止读取值。
  2. 学生的名字或姓氏可能由多个部分组成(例如“john john”,所以我使用 fgets 而不是 scanf 和 %s 来读取空格之后的单词,但它失败并且只有姓氏是已存储。

您能告诉我如何使用 EOF 停止循环并正确读取名字和姓氏吗?谢谢。

【问题讨论】:

  • 您检查过getcharfgetsscanf 调用返回的值吗?
  • 在不相关的注释中,您可能应该阅读并了解结构

标签: c loops scanf fgets eof


【解决方案1】:

为了检查 EOF ,你可以使用函数:

feof(FILE*) // if it returns 1 then it is EOF reached.

你可以像下面的 sn-p 一样使用它:

if (feof(fp) == 1)
break;

第二个问题:

printf("Enter last name of student %d: ",i+1);
    fgets(firstName[i],21,stdin); // this is incorrect.

使用“姓氏”而不是“名字”。应该是这样的:

fgets(lastName[i],21,stdin);

这样你就覆盖了名字的值

【讨论】:

  • 你可以使用类似的东西: if(getchar() == EOF) break;
  • 但是我应该把那个条件放在哪里?
  • 你在开始时使用 getchar 的地方
  • 即用于消费第三个值之后的回车
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2013-07-17
相关资源
最近更新 更多