在不按Enter的情况下获取单个字符 [英] Getting a single character without pressing enter
问题描述
我正在尝试从用户那里输入单个字符,而无需用户按Enter。我已经尝试过:
I'm trying to get a single character input from the user without the user having to press enter. I've tried this:
#include <stdio.h>
int main() {
int input;
for (;;) {
input = getchar();
printf("%d\n", input);
}
}
但用户不仅需要按Enter,它还记录了两次按下(输入字符和换行符),即:
But not only does the user need to press enter, it also registers two presses (the input character and the newline character) ie:
$ ./tests
a
97
10
c
99
10
因为我总是希望用户输入一个字符,并且希望将此字符作为 char
或 int
,如何在不等待 \n
的情况下获得角色。
Since I will always expect exactly one character input from the user, and want this character as either a char
or an int
, how can I get the character without waiting for a \n
.
我也尝试使用 fgets
,但是由于我在循环中等待用户输入,因此它会连续执行 printf
而不会阻塞直到输入。
I also tried using fgets
, but because I'm in a loop waiting for user input, that just continously executes the printf
without blocking until input.
我的预期输出为:
a97
b98
...
NB:我目前正在使用OSX,但我很高兴
NB: I'm currently on OSX but I'm happy with a solution that applies to either OSX or Linux.
推荐答案
我最近需要exac
I have recently needed exactly the same feature and I have implemented it in the following way:
#include <stdlib.h>
char c;
system("/bin/stty raw");
c = tolower(getchar());
system("/bin/stty cooked");
查看 man stty ,我认为它应该在Linux和Mac OS X上都可以使用。
Looking at man stty, I think it should work on both Linux and Mac OS X.
编辑:所以您的程序看起来像(您需要向其中添加信号处理程序):
So your program would look like (you would need to add a signal handler to it):
#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;
}
这篇关于在不按Enter的情况下获取单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!