【发布时间】:2024-01-06 05:25:01
【问题描述】:
book_name 选择 \n 作为输入,并在新行中打印下一个变量。我插入此代码while ((getchar()) != '\n'); 以防止 fgets() 在使用 scanf() 后将 \n 作为输入。但我不明白为什么 fgets() 将 \n 作为输入。请解释一下。
代码
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
char *book_name;
char *author;
} book;
int main() {
int n;
printf("Enter number of books: \n");
scanf("%d", &n);
book *bk = calloc(n, sizeof(book));
for (int i = 0; i < n; i++)
{
printf("Enter the no of the book: \n");
scanf("%d", &((bk+i)->id));
while ((getchar()) != '\n');
(bk+i)->book_name = malloc(20);
printf("Enter the name of the book: \n");
fgets((bk+i)->book_name, 20, stdin);
(bk+i)->author = malloc(20);
printf("Enter the author of the book: \n");
fgets((bk+i)->author, 20, stdin);
}
for (int i = 0; i < n; i++)
{
printf("%d %s %s\n", (bk+i)->id, (bk+i)->book_name, (bk+i)->author);
}
return 0;
}
输出
【问题讨论】:
-
"为什么 fgets() 将 \n 作为输入。" --> 这就是
fgets()所做的。 -
请注意,循环
while ((getchar()) != '\n');应该是int c; while ((c = getchar()) != EOF && c != '\n') ;— 如果您在读取换行符之前获得 EOF,您将在循环中花费很长时间(并且可能会发生!)。跨度> -
当有人输入诸如“灾难剖析”之类的标题(长度超过 18 个字符)时,您也会遇到问题。同样,如果“作者”是“威廉莎士比亚和弗朗西斯培根”,你就会遇到问题。您应该检查
scanf()和fgets()调用是否也成功。 I/O 有一个可怕的习惯,就是不检查就会失败。