Reading a single character in C

前端 未结 5 578
攒了一身酷
攒了一身酷 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 09:57

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

    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 2020-11-29 10:04

    To read just one char, use getchar instead:

    int c = getchar();
    if (c != EOF)
      printf("%c\n", c);
    
    0 讨论(0)
  • 2020-11-29 10:14

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

    scanf("%c\n",&in);
    
    0 讨论(0)
  • 2020-11-29 10:18

    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.

    0 讨论(0)
提交回复
热议问题