首页 > 解决方案 > 如何修复从 readline 输入到输出流

问题描述

我正在用 C++ 制作一个项目,我的任务是用 readline.h 库中功能更强大的 readline() 函数替换 std::getline,因为它包含更多功能,并且总体上会更有用。但是,我正在执行的程序对其他“in-X”文件进行多次测试,并生成“out-X”文件并检查输出结果以进行测试。

测试基本上是这样的

./a.exe < in-X.txt > out-X.txt

我遇到的问题是 readline() 函数似乎将它从输入读取的行打印到输出文件,所以基本上我生成的所有“out-X”文件都包含所有输入加上预期的结果,这是非常麻烦。

我已经尝试了许多 rl_redisplay() 组合并使用 rl_delete_text() 没有解决方案。我也尝试过使用终端管理功能,例如 rl_prep_terminal(1) 到原始模式和 rl_deprep_terminal() ,但似乎没有任何效果。我也无法尝试 rl_tty_set_echoing() 因为我的程序似乎无法在库中找到它。

我试图尽可能地减少这个问题并想出了这个简化的代码

/* Standard include files. stdio.h is required. */
#include <string.h>
#include <iostream>
#include <stdlib.h>

/* Standard readline include files. */
#include <readline/readline.h>
#include <readline/history.h>

int main(int argc, char* argv[]) {
  char *buf;
  while ((buf = readline("Prompt>")) != nullptr) {
    std::string line(buf);
    if (buf)
      add_history(buf);


    std::cout << "Line : " << line << "\n";
  }

  return 0;
}

这非常简单,打印 readline() 的提示不是输出预期的问题,而是打印读取的“buf”。

基本上用in文件

a = 2
b = 3
1 + 2 + 3

我希望输出

Line : a = 2
Line : b = 3
Line : 1 + 2 + 3

但我明白了

Prompt> a = 2
Line : a = 2
Prompt> b = 3
Line : b = 3
Prompt> 1 + 2 + 3
Line : 1 + 2 + 3
Prompt> 

包含 EOF 的最后一个“提示>”是我可以解决或使用的东西,但我不能打印第 3 行和第 5 行。

标签: c++readlinelibreadline

解决方案


推荐阅读