Another piece of information for @cooper1200. Keep in mind that reading from stdin (via scanf) isn't the same as reading directly from keyboard (which is more difficult to do). You are reading a "file" through a FILE pointer called stdin. Take a look at the code below:
Here are three ways to execute this code:Code:#include <stdio.h>
int main( void )
{
char c;
int count = 3;
puts( "Trying to read Y or N 3 times..." );
while ( count-- )
{
// this (or printf, puts, putchar) writes
// to stdout file stream.
fputs( "Type Y or N. ", stdout );
// stdout is 'line buffered'. It means that
// it can retain the chars until a '\n' is found.
// flushing the buffer garantees all chars will
// be dumped. The previous fputs didn't write
// the final \n, hence the flushing.
fflush( stdout );
// scanf reads data from stdin file stream.
// Note the space before %c will ignore all "spaces"
// as defined by isspace macro on ctype.h
scanf( " %c", &c );
switch (c)
{
case 'Y':
case 'y':
puts( "\nYes!" ); break;
case 'N':
case 'n':
puts( "\nNo!" ); break;
default:
printf( "\nFound '\\x%hhx' char. Hey! Y or N, remember?\n", c );
}
}
}
When you don't provide data for stdin (through pipe or redirection), functions as scanf() will wait for data coming from keyboard...Quote:
$ ./test
Trying to read Y or N 3 times...
Type Y or N. y
Yes!
Type Y or N. x
Found '\x78' char. Hey! Y or N, remember?
Type Y or N. n
No!
$ echo -e " y x \r\n\t\v\f n" | ./test
Trying to read Y or N 3 times...
Type Y or N.
Yes!
Type Y or N.
Found '\x78' char. Hey! Y or N, remember?
Type Y or N.
No!
$ echo -e " y x \r\n\t\v\f n" > ./input.txt
$ ./test < input.txt
Trying to read Y or N 3 times...
Type Y or N.
Yes!
Type Y or N.
Found '\x78' char. Hey! Y or N, remember?
Type Y or N.
No!
So, thinking abour stdin, stdout and stderr as "files" is useful...
PS: And yes... ignoring "spaces" before is better than after, in this case...