c program doesn't takes "space" as input to show the acsii code

The program shows output for all other characters instead of space. When I enter "space" it doesn't do anything and just waits.

#include<stdio.h>
#include<stdbool.h>

int main(){
    char c;
    while(true){
        printf("Enter character:");
        scanf("\n%c", &c);
        if (c == 27 )break;
        printf("ascii value:%d\n", c);

    }
    return 0;
}

The output for all other character comes fine.

Enter character:r
ascii value:114
Enter character:e
ascii value:101
Enter character:c
ascii value:99
Enter character:p
ascii value:112
Enter character:^[

I don't understand what's going on!

1 answer

  • answered 2022-05-04 10:54 chux - Reinstate Monica

    When I enter "space" it doesn't do anything and just waits.

    scanf("\n%c", &c); does not mean read a line-feed, then a character.
    Instead "\n%c" means to read any number of white-spaces like '\n', space, tab, .... and then read a character.

    OP's code is stuck reading white-spaces.

    Instead, read a line. Below has minimal testing and only pays attention to the first char in a line of input.

    // scanf("\n%c", &c);
    char buf[80];
    if (fgets(buf, sizeof buf, stdin) == NULL) {
      fprintf(stderr, "Input is closed\n");
      return -1;
    }
    c = buf[0];
    

    Remember the Enter is a char too.


    To read the escape character, other input functions may be needed.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum