我正在学习数据结构。我编写了一个简单的程序,要求用户填写有关购买 3 本书的信息。比如书名、作者、成本和页数。
但程序从来没有提示我最后一个问题(多少页)。但第二本书又开始循环。
struct bookinfo {
char title[40];
char author[25];
double price;
int pages;
}; // Header File "bookinfo"
#include "bookinfo.h"
#include <stdio.h>
int main(void)
{
int ctr;
struct bookinfo books[3]; // Array of three structure variables
// Get the information about each book from the user
for(ctr = 0; ctr < 3; ctr++)
{
printf("What is the name of the book #%d?\n", (ctr+1));
gets(books[ctr].title);
puts("Who is the author? ");
gets(books[ctr].author);
puts("How much did the book cost? ");
scanf(" $%f", &books[ctr].price);
puts("How many pages in the book? ");
scanf(" %d", &books[ctr].pages);
getchar(); // Clears last newline for the next loop
}
// Print a header line and then loop through and print the 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].author);
printf("\nIt is %d pages and cost $%.2f", books[ctr].pages, books[ctr].price);
printf("\n\n");
}
return (0);
}
你的第一个scanf
如果您没有在金额前准确输入 $,调用将会失败。因此,scanf
立即返回,第二个scanf
读取本应转到前一个的输入scanf
call.
Edit:抱歉,我没有提供信息来源。根据 scanf(3) 的手册页:
格式字符串由一系列指令组成,这些指令描述如何处理输入字符序列。如果指令处理失败,则不会读取进一步的输入,并且 scanf() 返回。 “失败”可以是
以下任一情况:输入失败,意味着输入字符不可用,或匹配失败,意味着输入不合适(见下文)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)