这个问题在这里已经有了答案:
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
因为我总是期望用户输入一个字符,并且希望这个字符作为
char
或 int
, 我怎样才能在不等待 \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/