
January 8th, 2013, 08:34 AM
|
 |
Contributing User
|
|
Join Date: Aug 2003
Location: UK
|
|
Standard input is line buffered so that scanf() does not return anything until there is a <newline> in the input buffer.
For scanf() whitespace is a field delimiter, so the scanf() call consumes the first value, leaving the second buffered. On the second scanf() call, it returns immediately because there is a <newline> already buffered. Note that the <newline> is not consumed by %d, so a subsequent input call will also return immediately.
One Solution:
Code:
printf("Enter 1st number");
scanf("%d",&a);
while( getchar() != '\n' ) { /* do nothing*/ }
printf("Enter 2nd number:");
scanf("%d",&b);
while( getchar() != '\n' ) { /* do nothing*/ }
Ideally you would wrap the input and buffer flushing into a single function to avoid repetition:
Code:
int enterDecimal( void )
{
int val ;
scanf( "%d", &val ) ;
while( getchar() != '\n' )
{
// do nothing
}
return val ;
}
then
Code:
printf("Enter 1st number");
a = enterDecimal() ;
printf("Enter 2nd number:");
b = enterDecimal() ;
Last edited by clifford : January 8th, 2013 at 08:40 AM.
|