c++ - OS X 使用箭头键移动终端插入符

标签 c++ c terminal command-line-interface

我制作了一个简单的 C 程序来演示这个问题。在这里。

#include <stdio.h>

int main(int argc, const char * argv[]) {
    char buffer[128];
    memset(buffer, 0, sizeof(buffer));

    printf("Type data:\n");
    scanf("%126s", buffer);

    printf("%s\n", buffer);

    getchar();
    return 0;
}

问题在于,当应用程序正在使用 scanf() 等待用户输入并且用户想要编辑他键入的行并使用箭头移动插入符号时,插入符号不会移动,但会插入新的丑陋输入。 enter image description here

出于某种原因,它没有以我期望的方式处理键。我也无法使用向上键转到上一个键入的行。

显然我应该故意启用此行为。你能给我建议吗?我该怎么做?

最佳答案

使用readline() .这是一个简单的例子:

#include <stdio.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <ctype.h>

#define MAX_LINE_LEN 80

int main() {
  char *line_buffer;
  int n, i;

  while (1) {
    line_buffer = readline("Say something: ");
    if (!line_buffer) break;
    for (i=0; line_buffer[i]; i++) {
      line_buffer[i] = toupper(line_buffer[i]);
    }
    printf("YOU SAID: %s\n",line_buffer);
  }
  putchar('\n');
  return 0;
}

/* (Compile with cc foo.c -lreadline -o foo) */

关于c++ - OS X 使用箭头键移动终端插入符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41122360/

相关文章:

c++ - 错误 : ISO C forbids declaration of `test' with no type

c - 管道到标准输出

c++ - Typedef 更改行为导致错误和警告

mongodb - 使用 zsh 在 Mac 上找不到 Mongo 命令?

c++ - type(myVar) 和 (type)myVar 有什么区别?

c++ - 将虚函数声明设置为零?

c - 如何在c中扫描输入数据?

haskell - 传递字符串以在终端中编辑,并在 Haskell 程序中使用 Enter 键确认

shell - 阻止Hadoop将JobClient输出发送到命令行?

c++ - Boost C++ 进程间