【发布时间】:2015-09-15 17:53:49
【问题描述】:
我不知道为什么,当我运行它时,它会跳过“书中有多少页”scanf 并直接进入第二个循环“谁是作者”。
我确定这与空白有关,但我认为我使用 for 循环底部的 getchar 解释了这一点。
标题:
struct bookInfo{
char title[40];
char author[25];
float price;
int pages;
};
.c 文件:
int main()
{
int ctr;
struct bookInfo books[3];
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 books cost");
scanf(" $%f", &books[ctr].price);
puts("how many pages in the book");
scanf(" %d", &books[ctr].pages);
getchar();
}
printf("here is the collection of books: \n");
for (ctr = 0; ctr <3; ctr++)
{
printf("book #%d: %s by %s", (ctr+1), books[ctr].title, books[ctr].author);
printf("\nit is %d pages and costs $%.2f", books[ctr].pages, books[ctr].price);
}
return 0;
}
【问题讨论】:
-
你记得输入美元符号
$吗?您应该始终检查来自scanf的返回值,以验证调用是否成功。 -
使用调试器是你的朋友。通常,这是一个比发布更好的朋友,因为调试器并不关心您描述的问题与您提供的代码一起没有意义(但您的帖子的读者可能会注意到这个细节)。
-
谢谢。问题是忘记了 $ - 多么迟钝哈哈。绝对不会再犯这个错误
-
函数:
gets()由于它的许多故障不再与我们同在。强烈建议使用fgets()