使用C或C++从控制台获取原始输入

Sha*_*awn 4 c c++ linux console-application

/* 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);
}
Run Code Online (Sandbox Code Playgroud)

如何将箭头键作为输入(可能作为单个字符),当前代码适用于我需要的所有其他东西...请不要使用ncurses解决方案

Ben*_*igt 6

你试过这个read功能吗?

这对我来说适用于 cygwin g++,没有 linux 方便测试:

#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); }
}
Run Code Online (Sandbox Code Playgroud)

正如@Fiktik 所指出的,回声设置已损坏,但我使用问题中的代码而未进行任何更改。


Bar*_*arc 6

有一个关于为 Unix 终端编写文本编辑器的很棒的教程,包括原始输入、语法着色等,它只使用标准 C 库和类 Unix 系统上可用的标准头文件:

https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html

本教程的这一章解释了如何将终端输入切换到原始模式并使用 C ( read()& stuff ) 中的标准 IO 函数对其进行处理。然后,您可以通过使用 VT100 终端的某些转义序列写入输出来处理光标移动、滚动、颜色等操作。您可以在本教程中找到更多信息,包括指向所有所需文档的链接和示例源代码。还有一个 GitHub 存储库,其中包含本教程中的所有示例以及最终产品,它基于antirez编写的Kilo 编辑器

至于读取特殊键,如箭头键、Home、End、PgUp、PgDown 等,尝试输出您从输入中获得的原始字符,然后按下您想要查看它们映射到的代码的键。对于箭头键,例如,它们通常映射到换码序列<ESC>[A通过<ESC>[D,其中<ESC>是用ASCII码的特殊控制字符27十进制或0x1B十六进制。这些是 VT100 终端转义码,指示终端将光标移动一个字符到这四个方向之一。在上述教程的下一章中更多地处理这些击键:

https://viewsourcecode.org/snaptoken/kilo/03.rawInputAndOutput.html


Hun*_*len 5

您无法在标准C++/C中执行此操作,您需要非标准的conio.h文件和getch()扩展名.然后你可以调用getch()两次来获取箭头的键代码

#include <conio.h>
using namespace std;

int main() 
{
    cout << "press up arrow;" << endl;
    int control = getch(); //gets the escape character
    int keycode = getch(); //gets the code
    cout << control << endl; 
    cout << keycode << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但 linux 不支持 conio.h。=( (3认同)