c 程序不将 "space" 作为输入来显示 ascii 码

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

程序显示所有其他字符而不是 space 的输出。当我输入“space”时,它什么也没做,只是等待。

#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;
}

所有其他字符的输出都正常。

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:^[

我不明白这是怎么回事!

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

scanf("\n%c", &c);不代表读一个line-feed,然后一个字符。
相反,"\n%c" 表示读取任意数量的 white-spaces,例如 '\n'、space、制表符……,然后读取一个字符。

OP 的代码无法读取 white-spaces。

改为阅读 。下面的测试很少,只关注输入的 中的第一个 char

// 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];

记住 Enter 也是 char


要读取escape字符,可能需要其他输入函数。

#include<stdio.h>
#include<stdlib.h>

void clear_buffer(){
    char ch;
    while(1){
        ch = getchar();
        if (ch == '\n' || ch == EOF ) break;
    }
}

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

函数clear_buffer清除缓冲区(输入字符被清除)以便只接受第一个字符,none之后的其他字符。