繁体   English   中英

跳过 c 中的 scanf 循环

[英]skipping over scanf loops in c

我不知道为什么,当我运行它时,它会跳过“书中有多少页” 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跳过前导空格。

其次,永远永远永远永远永远永远永远永远永远永远不要使用gets 曾经。 以任何方式,形状或形式。 (不是可能)在您的程序中引入故障点/主要安全漏洞。 它在 1999 年标准中已被弃用,并已从 2011 年标准中的标准库中删除。 它相当于在淋浴时拼接火线的编程。

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

那是因为 gets() 读取当前缓冲区中存在的文本行。 并且由于当前缓冲区包含“作者姓名是什么?” 它读取它。

如果您显示结构成员的内容,您可以清楚地观察到这一点。

所以我建议这个用途

    char *temp;
    fgets(STDIN,temp);

在循环开始之前。

这可以帮助你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM