首页 > 解决方案 > 避免来自 C 或 C++ 标准输入流的控制序列(如 ^[[C)

问题描述

代码:

#include <iostream>
#include <string>
using namespace std;

int main(){
    string s;
    cout << "Enter a string : " << endl;
    cin >> s;
    cout << "The Entered String is : " << s << endl;
    cout << "The Length of Entered String is : " << s.length() << endl;
    return 0;
}

输出:

┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $g++ -o trycpp -Os try.cpp
┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $./trycpp
Enter a string : 
hello
The Entered String is : hello
The Length of Entered String is : 5
┌─[jaysmito@parrot]─[~/Desktop]
└──╼ $./trycpp
Enter a string : 
hello^[[C
The Entered String is : hello
The Length of Entered String is : 8

如果您想要 C 中的代码,C 也会发生同样的事情,请索取!

当我按箭头键时 ^[[C 出现而不是光标移动(其他箭头键,转义键,home,end 也会发生类似的事情)!

这里发生的事情是字符串第二次包含字符:

['h', 'e', 'l', 'l', 'o', '\x1b', '[', 'C']

因此,'\x1b', '[', 'C' 是从键盘发送到外壳的字符序列,用于表示右箭头键(向前光标)。

我想要的是这些字符不会显示在外壳中,但光标会移动(根据按下的键向前、向后、到家、结束等)。

输入后的处理意义不大,因为主要目的是让光标移动!

我如何在 C 或 C++ 中实现这一点?

[编辑]

唯一的目标是在使用该程序时为用户提供类似终端的体验。

标签: c++shellinputstdin

解决方案


光标移动、功能键和其他特殊键在不同终端中的处理方式不同。但在大多数情况下,会生成一些转义序列

大多数语言中的程序提示都是简单的读取 from stdin,它将按原样读取转义序列。例如←[D←[C对应于左/右光标移动。

如果您想像prompt 一样处理这些转义序列bash,那么您需要自己做或者使用 3rd-party 库。

一个流行的是 GNU readline,但也有替代品,例如libedit.

这是一个带有libedit的演示程序(需要先安装libedit:)sudo apt install libedit-dev

#include <editline/readline.h>
#include <stdio.h>

int main() {
    char *line;
    while (line = readline("Enter input: ")) {
        printf("Entered: %s\n", line);
    }
    return 0;
}

编译并运行:

$ g++ test.cpp -o test -ledit
$ ./test

现在您应该能够使用左/右键在输入行中移动。


推荐阅读