第一个问题,为什么当我运行这个程序时它无法获取关于“scanf(” %d”, &books[ctr]->pages); 的用户数据?” ?它没有获取用户数据,而是重新启动循环。
第二个问题,谁能解释一下为什么getchar();在第一个循环结束时使用。如书中所述,它说“清除换行符输入”,但这对我来说真的没有意义。这与我遇到的问题有什么关系吗?
#include <stdio.h>
#include <stdlib.h>
struct bookInfo {
char title[40];
char auth[25];
float price;
int pages;
};
int main()
{
int ctr;
struct bookInfo * books[3];
//get info on books
for (ctr = 0; ctr < 3; ctr++)
{
books[ctr] = (struct bookInfo*)malloc(sizeof(struct bookInfo));
printf("What is the name of the book #%d?\n", (ctr+1));
fgets(books[ctr]->title, 40, stdin);
puts("Who is the author? ");
fgets(books[ctr]->auth, 25, stdin);
puts("How much did the book cost? ");
scanf(" $%f", &books[ctr]->price);
puts("How many pages are in the book? ");
scanf(" %d", &books[ctr]->pages);
getchar();
}
//print new header and then loop through and print info
printf("\n\nHere is the collection of books: \n");
for (ctr = 0; ctr < 3; ctr++)
{
printf("#%d: %s by %s", (ctr + 1), books[ctr]->title, books[ctr]->auth);
printf("\nIt is %d pages and costs $%.2f", books[ctr]->pages, books[ctr]->price);
printf("\n\n");
}
return(0);
}
我希望这个程序在完成循环并询问有关第 2 本书的信息之前收集书中的页数。然而……
当我运行程序时,这就是我得到的...
What is the name of the book #1?
good book
Who is the author? good author
How much did the book cost?
50
How many pages are in the book?
What is the name of the book #2?
bad book
Who is the author?
最佳答案
这里的问题是,您从未检查过 scanf()
的返回值!!
因此,按照您显示的输入,扫描语句(即 format
字符串)如下
scanf(" $%f", &books[ctr]->price);
50
的输入将导致匹配失败。因此,scanf()
将返回失败,然后输入将保留在输入缓冲区中,以供下一次成功调用 scanf()
时使用。在您的情况下,紧接的下一个转换规范似乎与输入完全匹配,因此您会得到 scanf()
从不等待 用户输入的行为。
相关,引用 C11
,章节 §7.21.6.2/P6,
A directive that is an ordinary multibyte character is executed by reading the next characters of the stream. If any of those characters differ from the ones composing the directive, the directive fails and the differing and subsequent characters remain unread. [....]
关于c - 为什么这个程序中的scanf()获取不到输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641549/