C - trying to read a single char from stdin (and failing) w/ scanf / getchar

You need a space between scanf(" and the %c for it to work correctly:

scanf(" %c", &choice);

And you also need to use &choice, not choice!

EDIT: While you're at it, you might want to look into do while() for that loop (unless the professor specifically said to use a break) - do while works great when validating user input!


fflush() is not defined by ISO C for input streams. It is defined in Microsoft's C runtime library, but is not portable.

While the "space before %c" solution may work when the user enters the expected data, it will fail in many ways; try entering "y n y n" for example. Console input is line oriented; your best bet is to ensure that you discard the entire line thus:

scanf( "%c", &choice ) ;
while( choice != '\n' && getchar() != '\n' ) /* do nothing*/ ;

Better still, use fgetc(). scanf() should always be a last resort.

Tags:

C

Scanf