scanf() 在 for 循环中被跳过 [英] scanf() gets skipped in for loop
本文介绍了scanf() 在 for 循环中被跳过的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Windows 中,我使用了 flushall() 函数来刷新所有缓冲区,但这在 Linux 中不起作用,我的 scanf() 函数会跳过而不扫描:
In Windows i used flushall() function to flush all the buffers but this doesnt work in Linux, my scanf() function skips without scanning:
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
开头加一个空格,fflush(stdin)
scanf
只是为了清除标准输入缓冲区(默认是键盘),像这样:
You should add a space on the beginning of the scanf
, and fflush(stdin)
before every scanf
just to clear the standard input buffer (keyboard by default), like this:
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 概率
这篇关于scanf() 在 for 循环中被跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文