且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

混淆了scanf的行为

更新时间:2022-10-21 22:12:57

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


int main()

{

int num [4],i = 0;

char ch;


do

{

do

{

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

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

i ++;

} while(i

fflush( stdin);

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

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

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


返回0;


}


2005-12-21,alok< al ****** @ gmail.com>写道:
添加fflush(stdin)清除输入缓冲区




编号


嗨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