16

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

fresskoma
  • 25,481
  • 10
  • 85
  • 128
g3d
  • 453
  • 2
  • 6
  • 14

5 Answers5

40
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 
P.P
  • 117,907
  • 20
  • 175
  • 238
  • Actually I want to create a char array.Do have an idea about it? (Input size is uncertain).Thanks! – g3d Jan 19 '13 at 23:36
  • @vkeles: 1) Allocate an array with some initial size, say `n` using `malloc` 2) Read chars into the array until the it doesn't exceed `n` 3) If `n` chars are read and you want to read more than double the size of the array using `realloc`. This method is generally followed to avoid calling realloc too frequently. Otherwise, you may do the realloc with your preferred size. – P.P Jan 19 '13 at 23:48
6

To read just one char, use getchar instead:

int c = getchar();
if (c != EOF)
  printf("%c\n", c);
Douglas
  • 36,802
  • 9
  • 76
  • 89
3

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

scanf("%c\n",&in);
Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118
  • I could not get scanf("%c\n", &in); to work properly. This does work however: scanf(" %[^\n]%*c", &in); The %*c tells scanf to read and discard anything left in the input buffer including newlines. It is always good practice to include a space right after the first " used in scanf. But if you want to preserve the white entered by the user (e.g. spaces before other text is entered), then omit the space following the first " in scanf(). – RobK Jul 16 '21 at 15:59
0

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

umsee
  • 21
  • 4
-1

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.

  • Note that this example doesn't allocate any memory for the character array, nor does it set the initial value of ar, so it will write to an effectively random location in memory, overwriting whatever is there. – Douglas Jan 20 '13 at 10:27
  • Thank you.I really forget to keep the habit to initialize a pointer variable – Cocoo Wang Jan 20 '13 at 16:40