c - 不按回车键获取单个字符

标签 c input character fgets getchar

这个问题在这里已经有了答案:





What is the equivalent to getch() & getche() in Linux?

(6 个回答)


6年前关闭。




我正在尝试从用户那里获取单个字符输入,而无需用户按 Enter。我试过这个:

#include <stdio.h>

int main() {
    int input;

    for (;;) {
        input = getchar();
        printf("%d\n", input);
    }
}

但用户不仅需要按回车键,还需要注册两次按(输入字符和换行符),即:
$ ./tests
a
97
10
c
99
10

因为我总是期望用户输入一个字符,并且希望这个字符作为 charint , 我怎样才能在不等待 \n 的情况下获得字符.

我也尝试使用 fgets ,但是因为我在一个循环中等待用户输入,所以它只是不断地执行 printf不阻塞直到输入。

我的预期输出是:
a97
b98
...

注意:我目前使用的是 OSX,但我对适用于 OSX 或 Linux 的解决方案感到满意。

最佳答案

我最近需要完全相同的功能,我已通过以下方式实现它:

#include <stdlib.h>

char c;

system("/bin/stty raw");
c = tolower(getchar());
system("/bin/stty cooked");

看着 man stty ,我认为它应该适用于 Linux 和 Mac OS X。

编辑:所以你的程序看起来像(你需要向它添加一个信号处理程序):
#include <stdlib.h>
#include <stdio.h>

int main() {
    int input;

    for (;;) {
        system("/bin/stty raw");
        input = getchar() - '0';
        printf("%d\n", input);
        system("/bin/stty cooked");
    }
    return 0;
}

关于c - 不按回车键获取单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32781937/

相关文章:

c - 自定义 strcmp 中的奇怪错误 (C)

c - C 中的基本字符计数

c - 使用 System.security.cryptography 将使用 OpenSSL 进行公钥身份验证的 C 代码转换为 VisualBasic.NET?

python - Numpy数组切片转置内部数据

c - 如何打开我的 .sgrd 文件?

c - 对用户输入设置时间限制

python - 计算字符串中的特定字符 - Python

c - C 中函数的 char 指针是否需要内存分配

java - libgdx touchup 和 touchdragged 没有被调用,但是 touchdown 是

c - 使用 getchar 和存储字符时遇到困难