gpt4 book ai didi

c - 跳过c中的scanf循环

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:40 25 4
gpt4 key购买 nike

我不知道为什么,当我运行它时,它会跳过“这本书有多少页” 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;
}

最佳答案

改变这个:

puts("how much did the books cost");
scanf(" $%f", &books[ctr].price);

为此:

printf("how much did the books cost: $");
fflush( stdout );
scanf("%f", &books[ctr].price);

除非您打算让您的用户在价格前键入一个 $,否则会很烦人。您不需要格式字符串中的前导空格,因为 %f 告诉 scanf 跳过前导空格。

其次,NEVER NEVER NEVER NEVER NEVER NEVER NEVER NEVER 使用gets。曾经。以任何方式、形状或形式。它(不一定,)在您的程序中引入故障点/主要安全漏洞。它在 1999 标准中被弃用,并从 2011 标准开始从标准库中删除。这相当于在淋浴时拼接带电电线的编程。

使用 fgets(与 gets 不同,如果有空间,它将尝试将换行符存储在目标缓冲区中)或 scanf(在转换说明符中使用适当的精度)代替。

关于c - 跳过c中的scanf循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com