How to do scanf for single char in C

Yuval picture Yuval · Nov 24, 2012 · Viewed 463.1k times · Source

In C: I'm trying to get char from the user with scanf and when I run it the program don't wait for the user to type anything...

This is the code:

char ch;
printf("Enter one char");
scanf("%c", &ch);
printf("%c\n",ch);

Why is not working?

Answer

John Bode picture John Bode · Nov 24, 2012

The %c conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately.

One way around the problem is to put a blank space before the conversion specifier in the format string:

scanf(" %c", &c);

The blank in the format string tells scanf to skip leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.