我不知道为什么,当我运行它时,它会跳过"书中有多少页" scanf并直接进入第二个循环"谁是作者".
我确定这与空白有关,但我认为我用getcharfor循环的底部来解释这个问题.
标题:
struct bookInfo{
char title[40];
char author[25];
float price;
int pages;
};
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
改变这个:
puts("how much did the books cost");
scanf(" $%f", &books[ctr].price);
Run Code Online (Sandbox Code Playgroud)
对此:
printf("how much did the books cost: $");
fflush( stdout );
scanf("%f", &books[ctr].price);
Run Code Online (Sandbox Code Playgroud)
除非您打算让您的用户$在价格之前键入一个,这将是烦人的.您不需要格式字符串中的前导空格,因为它%f告诉scanf跳过前导空格.
其次,永远不会永远不会永远不会使用gets.永远.无论如何,形状或形式.它会(不是可能,将)在程序中引入故障/严重的安全漏洞的一个点.它在1999年标准中已被弃用,并已从2011标准中删除.这是编程相当于在淋浴时拼接带电线.
使用fgets(不同的是gets,如果有空间,将尝试将换行符存储在目标缓冲区中)或scanf(在转换说明符中具有适当的精度).