Re: scanf behaviour



stasgold@xxxxxxxxx wrote:
Hello.

I maybe reinvent the weel ...
I'm trying to read positive integer number with the help of scanf, if
the input value is not positive number but negaive one zero or char , i
have to reread the input until I get the needed pos. number

I wrote the code , but it doesn't work the way it should : if i put
some char into input, the program goes infinite loop instead of
promting me to enter a new value.

That's because the conversion fails and the characters remain in the
stream. So the next time scanf is called, the same character sequence is
read.

Add

fflush( stdin );

after your printf.

Please shed some light on what is the problem. thanks
[code]
#include <stdio.h>

int main()
{
int n;
while (1)
{
printf("Please enter positive number \n");
if ( scanf("%d",&n)!=1 || n<=0 )
{
printf("Illegal input!\n");
continue;
}

return 0;
}
return 1;
}
[/code]



--
Ian Collins.
.



Relevant Pages