gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:48:54 27 4
gpt4 key购买 nike

我知道这是一个奇怪的问题,但是有什么方法可以从控制台读取以前的输入吗?

类似于:

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

附言:我使用的是 windows

最佳答案

如果通过阅读先前的输入,您的意思是从 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';
}

关于c++ - 从控制台 C++ 读取已输入的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39797734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com