[英]scanf() gets skipped in for loop
In Windows i used flushall() function to flush all the buffers but this doesnt work in Linux, my scanf() function skips without scanning: 在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);
}
Output : 输出:
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 :
Update: The OP changed the "%d"in the first scanf to "%c" which lets the error, I think, occur later; 更新: OP将第一个scanf中的“%d”更改为“%c”,我认为该错误会在以后发生; but franky, I don't feel investing any more time here.--
但坦率地说,我不想在这里花更多的时间。
Original answer: The input is never processed beyond the 'a' because you try reading it with the conversion specification %d for integer numbers which it doesn't satisfy. 原始答案:永远不会处理超出'a'的输入,因为您尝试使用转换说明%d读取它不满足的整数。 (In order to read a char you would specify %c.) Scanf puts the offending character back in the input and tries to read the next number which fails again, and so on ad eternum.
(为了读取一个字符,您可以指定%c。)Scanf将有问题的字符放回输入中,并尝试读取下一个再次失败的数字,以此类推。
It's worth checking scanf's return value which will always be 0 here, indicating that no successful conversion has taken place. 值得检查scanf的返回值,这里的返回值始终为0,表示没有成功进行转换。
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: 您应该在
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);
}
EDIT: check if you have char x
and float probability
编辑:检查您是否具有
char x
和float probability
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.