c++ - 避免来自 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++ 中实现这一点?
[编辑]
唯一的目标是在使用该程序时为用户提供类似终端的体验。
解决方案
光标移动、功能键和其他特殊键在不同终端中的处理方式不同。但在大多数情况下,会生成一些转义序列。
大多数语言中的程序提示都是简单的读取 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
现在您应该能够使用左/右键在输入行中移动。
推荐阅读
- c# - 程序集重定向未指向预期的程序集
- r - paste(v, collapse = "\n") 中的错误:结果将超过 2^31-1 个字节
- node.js - scss 错误“预期媒体查询” - 使用多个媒体查询 - 标准化设备的大小
- android - PreferenceScreen 之间的分隔符
- mysql - MySQL Before Delete 触发器避免删除多行
- css - CSS动画线在悬停时增长
- android - Android:在 webview 中下载在 oreo 中不起作用,它在 Oreo 设备中强制关闭
- python - 如何只调用并过滤一只股票到这个索引名称很长的df?
- unity3d - 如何使用自定义编辑器属性从任何地方获取屏幕点击输入?
- codenameone - 如何在 PropertyBusinessObject json 中包含嵌套的 PropertyBusinessObject?