c - scanf() 在 for 循环中被跳过

标签 c scanf

在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 :

最佳答案

您应该在 scanf 的开头添加一个空格,并在每个 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 x float 概率

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

相关文章:

c - 如何检查多表C程序中输入的整数?

c - mingw 环境中 64 位字符串格式化程序的警告

c - malloc 问题?

c - 从 switch case 或循环中的输入获取带空格的字符串

c - 我不断收到与类型相关的错误

c - (C) 在 printf 行显示多个变量,有一些问题

c - AIX 上的函数指针编译错误

c - 尝试释放内存时出错

c# - 在实际应用方面,C、C# 和 C++ 之间有什么区别?

将指针转换为指向数组的指针