混淆了scanf的行为 [英] confused about behaviour of scanf

查看:65
本文介绍了混淆了scanf的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友们,

我在代码中遇到问题时与嵌套进行交互

Do-while循环

它正在跳过一个不应该的scanf()函数。我在下面写了整个代码,写了

。请帮助我找到为什么这样的事情发生了什么以及它的补救措施是什么。请耐心等待我的英语。

int

main()

{

int num1 [4],i = 0;

char ch;


do

{

do

{

printf(输入数组中的数字\ n);

scanf("%d",& num [i] );

i ++;

} while(i <= 3);


printf(你想补充吗?数组再次y / n

\ n");

scanf("%c",& ch); / *这一行被跳过,它是

不是

提示

从键盘输入

来自键盘/>
* /


} while(ch = =''y''); / *在gdb''ch'中是

显示的值与

相同,它在声明时就是

一些垃圾* /


返回0;

}


我知道这对你们很多人来说都是非常愚蠢的问题但仍然我在

模糊处理它。所以请把所有可能的方式发给我

解决它。为什么会出现这样的问题。

我所做的环境是gcc-3.2.2,red hat Linux -9,使用gdb调试。

解决方案

添加fflush(stdin)清除输入缓冲区


int main()

{

int num [4],i = 0;

char ch;


do

{

do

{

printf("输入数组中的数字\ n);;

scanf("%d" ,& num [i]);

i ++;

} while(i <= 3);


fflush( stdin);

printf(你想再次重新填充阵列y / n \ n);

scanf("%c",&) ch);

} while(ch ==''y'');


返回0;


}


2005-12-21,alok< al ****** @ gmail.com>写道:

添加fflush(stdin)清除输入缓冲区




编号


< blockquote>嗨Lalatendu,


在外循环之后输入流中有''\ n'',它然后

被读取scanf(%c,& ch)。 (你可以在这个

行之后在gdb中看到它。)


您可以使用fflush(stdin)清除不需要的''\ n' '在下次扫描之前

值。


马特


Dear friends,
I am getting a problem in the code while interacting with a nested
Do-while loop
It is skipping a scanf () function which it should not. I have written
the whole code below. Please help me in finding why such thing is
happening and what the remedy to it is. Kindly bear with my English.
int
main ()
{
int num1[4] , i = 0 ;
char ch ;

do
{
do
{
printf ("Enter the number in the array \n");
scanf("%d",&num[i] );
i++;
} while (i<=3);

printf("Do u want to refill the array again y/n
\n");
scanf ("%c", &ch); /* This line is skipped, it
is not
prompting to
give input
from keyboard
*/

} while (ch = = ''y'') ; /* In gdb ''ch'' is
showing the value same as
it has at the time of declaration i.e.
some garbage */

return 0;
}

I know this is very silly question for many of u but still I am in
ambiguity to resolve it . So please send me all possible way of
resolving it. and why such problem occurring. The environment in which
I have done it is gcc-3.2.2, red hat Linux -9 , debugged using gdb .

解决方案

add fflush(stdin) to clear input buffer

int main ()
{
int num[4] , i = 0 ;
char ch ;

do
{
do
{
printf ("Enter the number in the array \n");
scanf("%d",&num[i] );
i++;
} while (i<=3);

fflush(stdin);
printf("Do u want to refill the array again y/n\n");
scanf ("%c", &ch);
} while (ch == ''y'') ;

return 0;

}


On 2005-12-21, alok <al******@gmail.com> wrote:

add fflush(stdin) to clear input buffer



No.


Hi Lalatendu,

There''s a ''\n'' remainning in input stream after the outer loop, it then
was read by scanf ("%c", &ch). (you can see it in gdb just after this
line).

You can use fflush(stdin) to clean the unwanted ''\n'' before scanf next
value.

Matt


这篇关于混淆了scanf的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆