#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>
// 获取终端输入模式
termios getTerminalMode() {
termios mode;
tcgetattr(STDIN_FILENO, &mode);
return mode;
}
// 设置终端输入模式
void setTerminalMode(termios mode) {
tcsetattr(STDIN_FILENO, TCSANOW, &mode);
}
// 禁用终端回显和行缓冲
void disableTerminalEcho() {
termios mode = getTerminalMode();
mode.c_lflag &= ~(ICANON | ECHO);
setTerminalMode(mode);
}
// 启用终端回显和行缓冲
void enableTerminalEcho() {
termios mode = getTerminalMode();
mode.c_lflag |= ICANON | ECHO;
setTerminalMode(mode);
}
// 获取终端输入的字符
int getChar() {
int ch;
disableTerminalEcho();
ch = getchar();
enableTerminalEcho();
return ch;
}
// 移动光标到指定位置
void moveCursor(int pos) {
std::cout << "\033[" << pos << "G";
}
// 删除指定位置的字符
void deleteChar(std::string& input, int pos) {
if (pos > 0 && pos <= input.length()) {
input.erase(pos - 1, 1);
}
}
int main() {
std::string input;
std::cout << "dd: "<<std::endl;
std::cout.flush();
int ch;
int cursorPos = 0;
moveCursor(0 + 1);
while ((ch = getChar()) != '\n') {
if (ch == 27) { // 方向键
ch = getChar();
if (ch == 91) {
ch = getChar();
if (ch == 68) { // 左箭头
if (cursorPos > 0) {
cursorPos--;
moveCursor(cursorPos + 1);
}
} else if (ch == 67) { // 右箭头
if (cursorPos <= input.length()) {
cursorPos++;
moveCursor(cursorPos + 1);
}
}
}
} else if (ch == 127) { // 退格键
if (cursorPos > 0) {
moveCursor(cursorPos);
deleteChar(input, cursorPos );
cursorPos--;
std::cout << input.substr(cursorPos) << " ";
moveCursor(cursorPos + 1);
}
} else {
input.insert(cursorPos , 1, ch);
cursorPos++;
moveCursor(cursorPos);
std::cout << input.substr(cursorPos - 1);
moveCursor(cursorPos + 1);
}
}
std::cout << std::endl;
input.push_back('\0');
std::cout << "Input: " << input << std::endl;
std::cout << "Exiting the program. Goodbye!" << std::endl;
return 0;
}
调试程序,实现了命令行下输入字符串,支持修改,回调
于 2023-07-20 11:04:33 首次发布