scanf() 在 for 循环中被跳过

scanf() gets skipped in for loop

在 Windows 中,我使用 flushall() 函数来刷新所有缓冲区,但这在 Linux 中不起作用,我的 scanf() 函数在没有扫描的情况下跳过:

for(i=0;i<n;i++)
   {
    printf("\nEnter alphabet :");
    scanf("%c",&x);
    printf("\nEnter frequency :");
    scanf("%f",&probability);
  /* create a new tree and insert it in
     the priority linked list */
    p=(treenode*)malloc(sizeof(treenode));
    p->left=p->right=NULL;
    p->data=x;
    p->freq=(float)probability;
    head=insert(head,p);
  }

输出:

mayur@mayur-laptop:~$ ./a.out

Enter alphabet :a

Enter frequency :2

Enter alphabet :
Enter frequency :a

Enter alphabet :
Enter frequency :2

Enter alphabet :
Enter frequency :a

Enter alphabet :

更新: OP 更改了“%d"in the first scanf to "%c”,我认为这让错误稍后发生;但是弗兰基,我不想再花时间在这里了。--

原始答案: 永远不会处理超出 'a' 的输入,因为您尝试使用它不满足的整数转换规范 %d 来读取它. (为了读取一个字符,您可以指定 %c。)Scanf 将有问题的字符放回输入中并尝试读取下一个再次失败的数字,依此类推。

值得检查一下 scanf 的 return 值,这里始终为 0,表示没有成功转换。

您应该在 scanf 的开头添加一个 space,并且在每个 scanf 之前添加一个 fflush(stdin) 只是为了清除标准输入缓冲区(默认为键盘) ,像这样:

for(i=0;i<n;i++){
    printf("\nEnter alphabet :");
    fflush(stdin);
    scanf(" %c",&x);
    printf("\nEnter frequency :");
    fflush(stdin);
    scanf(" %f",&probability);
  /* create a new tree and insert it in
     the priority linked list */
    p=(treenode*)malloc(sizeof(treenode));
    p->left=p->right=NULL;
    p->data=x;
    p->freq=(float)probability;
    head=insert(head,p);
  }

编辑:检查您是否有 char xfloat probability