从控制台 C++ 读取已经输入的行

Nic*_*lus 1 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
Run Code Online (Sandbox Code Playgroud)

PS:我正在使用窗户

dka*_*man 5

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

快速而肮脏地展开流并读取同一行两次

#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';
}
Run Code Online (Sandbox Code Playgroud)

  • [`unget` 将最后一个字符放回流中](http://en.cppreference.com/w/cpp/io/basic_istream/unget)。其他注意事项:尝试使用 `seekg` 来做同样的事情是......好吧,我在 [标准工作草案副本](http://open-std.org/JTC1/SC22/WG21) 中找不到任何明确的内容/docs/papers/2016/n4606.pdf) 是免费提供的,但它正在寻找实现定义。不要指望 `seekg` 工作。 (2认同)