g3d
g3d

Reputation: 451

Reading a single character in C

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

Upvotes: 16

Views: 126264

Answers (5)

Manolis Ragkousis
Manolis Ragkousis

Reputation: 665

in scanf("%c",&in); you could add a newline character \n after %c in order to absorb the extra characters

scanf("%c\n",&in);

Upvotes: 3

umsee
umsee

Reputation: 21

you could always use char a = fgetc (stdin);. Unconventional, but works just like getchar().

Upvotes: 0

Cocoo Wang
Cocoo Wang

Reputation: 9

you can do like this.

char *ar;
int i=0;
char c;
while((c=getchar()!=EOF)
   ar[i++]=c;
ar[i]='\0';

in this way ,you create a string,but actually it's a char array.

Upvotes: -1

P.P
P.P

Reputation: 121387

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 

Upvotes: 40

Douglas
Douglas

Reputation: 37763

To read just one char, use getchar instead:

int c = getchar();
if (c != EOF)
  printf("%c\n", c);

Upvotes: 6

Related Questions