问题描述
让我们想象一下我的程序在不同时间需要用户输入。
我希望此输入防止刷新cout
缓冲区。
我可以在不同的流缓冲区上设置cin
和cout
吗?
所讨论的示例:一个程序读取一行n1 n2
中的两个数字,并且取决于第一个数字是0
,1
或2
:
-
n1 = 0
:将第二个数字n2
写入向量v
-
n1 = 1
:在v[n2]
中输出cout
-
n1 = 2
:pop_back()
上的v
MWE为:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int size,n1,n2;
vector<int> v;
cin >> size;
while(size--){
cin >> n1;
if (n1 == 0)
{
cin >> n2;
v.push_back(n2);
}
else if (n1 == 1)
{
cin >> n2;
cout << v[n2] << '\n';
}
else if (n1 == 2)
v.pop_back();
}
return 0;
}
说我有这个测试输入
8
0 1
0 2
0 3
2
0 4
1 0
1 1
1 2
正确的输出应该是
1
2
4
上面的程序产生的输出代替输入行。
但是我希望它们都在最终程序中一起打印,而无需使用其他方法,例如将它们存储在某些容器等中。
所以我认为我应该对缓冲区进行操作,但是如何?
解决方法
您可以写入自己的std::stringstream
缓冲区,然后在准备好之后将其输出到std::cout
。
MWE:
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
using std::cin;
using std::cout;
using std::istream;
using std::runtime_error;
using std::stringstream;
using std::vector;
static auto get_int(istream& in) -> int {
int n;
if (!(in >> n)) {
throw runtime_error("bad input");
}
return n;
}
int main() {
auto ss = stringstream();
auto v = vector<int>();
auto size = get_int(cin);
while(size--) {
auto n1 = get_int(cin);
if (n1 == 0) {
auto n2 = get_int(cin);
v.push_back(n2);
} else if (n1 == 1) {
auto n2 = get_int(cin);
ss << v[n2] << '\n';
} else if (n1 == 2) {
v.pop_back();
}
}
cout << ss.str();
}
,
无需修改缓冲区。除了将cout << v[n2]
存储在第二个向量中之外,还可以将其v[n2]
打印在循环的外部。