-
weird scanf()
take a look at this piece of code...
Code:
#include <stdio.h>
int main( void )
{
int i = 0, c = 0, sent = 0;
char str[ 30 ];
printf( "Choose ( 0 to this, 1 do that ) : " );
scanf( "%d", &sent );
if( sent )
;/* do stuff */
else {
printf( "Please input a string of text : \n" );
while( ( c = getchar() ) != '\n' )
str[ i++ ] = c;
str[ i ] = '\0';
printf( "The string entered was : \n" );
puts( str );
}
return 0;
}
if the sentinel value is 0 it seems that getchar() takes
the newline char that i inputed in order to scanf() the sentinel
value.
I thought that scanf() doesn't leave the newline char in stdin,
so that i don't have to fflush() it.
Any comments on that ?
trekker
-
>I thought that scanf() doesn't leave the newline char in stdin
Yes, it does. You can read about many people's woes by searching for the many hundreds of posts about scanf in the board search utility.
>so that i don't have to fflush() it.
You'd better not anyway, fflush is not defined for input streams. When I say that most people seem to shrug it off as useless information so I'll rephrase it. Using fflush ( stdin ); is wrong and can ruin your computer. That's a worst case scenario, but undefined behavior brings this into the realm of possibility. Try something along the lines of this:
Code:
#include <stdio.h>
#define FLUSH_STDIN while ( getchar() != '\n' )
int main( void )
{
int i = 0, c = 0, sent = 0;
char str[ 30 ];
printf( "Choose ( 0 to this, 1 do that ) : " );
scanf( "%d", &sent );
FLUSH_STDIN;
if( sent )
;/* do stuff */
else {
printf( "Please input a string of text : " );
while( ( c = getchar() ) != '\n' )
str[ i++ ] = c;
str[ i ] = '\0';
printf( "The string entered was : " );
puts( str );
}
return 0;
}
-Prelude