在列表中阅读
问题描述:
我必须编写一个程序,读取学生姓名和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停止。
- 学生的名字或姓氏可能由多个部分组成(类似于“约翰约翰”,所以我用fgets代替了scanf和%s来读取空格后的单词,但它失败了,只有姓氏是。?存储
你能告诉我如何停止与EOF循环和读出第一和最后一个名称正确由于
答
用于检查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.
使用 '姓氏' 而不是 '名字'。它应该是这样的:
fgets(lastName[i],21,stdin);
以这种方式要覆盖名字的价值
+0
哦,权利thnaks我没有看到它! –
+0
乐意帮助伙计! –
+0
它仍然读入。我怎么能删除它们? –
你检查你的['getchar'(http://en.cppreference.com/返回的值w/c/io/getchar),['fgets'](http://en.cppreference.com/w/c/io/fgets)和['scanf'](http://en.cppreference.com/ w/c/io/fscanf)来电? –
在不相关的说明中,您应该阅读并学习*结构*。 –