跳过c中的scanf循环

Dan*_*iel 2 c scanf

我不知道为什么,当我运行它时,它会跳过"书中有多少页" 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)

Joh*_*ode 5

改变这个:

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(在转换说明符中具有适当的精度).

  • @ i486:正确.`gets`不知道目标缓冲区有多大,如果用户输入的缓冲区大小要容纳更多文本,那么`gets`会很乐意将该额外文本写入紧跟目标缓冲区的内存中,导致各种混乱.`fgets`允许你指定从输入流中读取的最大字符数,使它更安全一些(显然,你必须传递正确的值,所以它不是完全万无一失,但它并不是一个巨大的安全漏洞.得到`是).截至2011年的标准,不再支持`gets`. (5认同)