从Console C ++中读取已经输入的行

时间:2016-09-30 18:21:06

标签: c++ input console-input

我知道这是一个奇怪的问题,但有没有办法从控制台读取以前的输入。类似的东西:

The fox is brown // line 1
The duck is yellow // line 2
Here where the control is right now_ // but I want to read line 2

P.S:我正在使用Windows

3 个答案:

答案 0 :(得分:3)

如果通过阅读上一个输入,您的意思是在C ++程序中,答案是肯定的。标准输入是stream,它维护一个读缓冲区。

快速和脏,以放松流并读取相同的行两次

#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << "Enter a line of text and you will see it echo twice\n";

    string mystring;
    getline(cin, mystring);
    cout << mystring;

    cout << "\n";

    // reverse the input stream by the lengtht of the read string (+1 for the newline)
    for (int i = 0; i <= mystring.length(); i++)
    {
        cin.unget();
    }

    string mystring2;
    getline(cin, mystring2);
    cout << mystring2;

    cout << '\n';
}

答案 1 :(得分:1)

可以通过一些假设来完成,但会带来一些您可能会发现过于严格的限制。所以最好找到一种不这样做的方法。

使用ncurses库,您可以完全控制终端和读/写符号到屏幕上的任何位置。但是如果你这样做,你将负责控制它,这包括滚动文本。除非您自己实现,否则也无法滚动终端。除此之外,您还需要牢记屏幕尺寸并处理它的变化。请注意,您的程序也可以在不支持该模式的终端下启动。

所以,如果可以将用户输入存储在程序中而不是将其存储在屏幕上,请不要弄乱它。

答案 2 :(得分:0)

这看起来非常接近。

  

历史|尾巴-n 2

相关问题