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'?
A single character may be read as follows: char c; scanf_s("%c", &c, 1);
The single character input/output functions are Getchar () and putchar (). Getchar() is used to get a single character and require key after input.
A getchar() reads a single character from standard input, while a getc() reads a single character from any input stream. It does not have any parameters.
In C char is the data type that represents a single character. The char values are encoded with one byte code, by the ASCII table.
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
To read just one char, use getchar instead:
int c = getchar();
if (c != EOF)
printf("%c\n", c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With