Reading a single character in C

前端 未结 5 608
攒了一身酷
攒了一身酷 2020-11-29 09:27

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

Input:

a

Output:



        
5条回答
  •  忘掉有多难
    2020-11-29 10:04

    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 
    

提交回复
热议问题