使用C或C ++从控制台获取原始输入 [英] Getting raw input from console using C or C++
本文介绍了使用C或C ++从控制台获取原始输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
/* Initialize new terminal i/o settings */
static struct termios old, new1;
void initTermios(int echo) {
tcgetattr(0, &old); /* grab old terminal i/o settings */
new1 = old; /* make new settings same as old settings */
new1.c_lflag &= ~ICANON; /* disable buffered i/o */
new1.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new1); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void) {
tcsetattr(0, TCSANOW, &old);
}
如何获取箭头键作为输入(可能是单个字符),当前代码对我需要的所有其他东西都适用...请使用 ncurses
How can I get arrow key as input (possibly as a single character), the current code works good for all other things I need... Please no solution with ncurses
推荐答案
您是否尝试过read
函数?
这对cygwin g ++来说适用于我,不需要Linux即可方便地进行测试:
This works for me with cygwin g++, don't have linux handy to test:
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
/* Initialize new terminal i/o settings */
static struct termios old, new1;
void initTermios(int echo) {
tcgetattr(0, &old); /* grab old terminal i/o settings */
new1 = old; /* make new settings same as old settings */
new1.c_lflag &= ~ICANON; /* disable buffered i/o */
new1.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new1); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void) {
tcsetattr(0, TCSANOW, &old);
}
int main(void)
{
char c;
initTermios(0);
while (1) { read(0, &c, 1); printf("%d\n", c); }
}
正如@Fiktik指出的那样,回声设置已损坏,但我使用的是问题中的代码,未做任何更改.
As @Fiktik noted, the echo setup is broken, but I'm using the code in the question without changes.
这篇关于使用C或C ++从控制台获取原始输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文