Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a single character in C

Tags:

c

scanf

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'?

like image 911
g3d Avatar asked Jan 19 '13 23:01

g3d


People also ask

How do you read a character in C?

A single character may be read as follows: char c; scanf_s("%c", &c, 1);

Which function is read single character in C?

The single character input/output functions are Getchar () and putchar (). Getchar() is used to get a single character and require key after input.

What reads a single character?

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.

What is a single character in C?

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.


2 Answers

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 
like image 165
P.P Avatar answered Sep 19 '22 19:09

P.P


To read just one char, use getchar instead:

int c = getchar();
if (c != EOF)
  printf("%c\n", c);
like image 39
Douglas Avatar answered Sep 17 '22 19:09

Douglas