Reading a single character in C

g3d picture g3d · Jan 20, 2013 · Viewed 92.3k times · Source

I'm trying to read a character from the console (inside a while loop). But it reads more than once.

Input:

a

Output:

char : a  char : char : '

Code:

while(..)
{
    char in;
    scanf("%c",&in);
}

How can i read only 'a'?

Answer

P.P picture P.P · Jan 20, 2013
scanf("%c",&in);

leaves a newline which is consumed in the next iteration.

Change it to:

scanf(" %c",&in); // Notice the whitespace in the format string

which tells scanf to ignore whitespaces.

OR

scanf(" %c",&in);
getchar(); // To consume the newline