[英]How to prevent `std::cin` or `\n` from flushing the buffer of `std::cout`?
Let's imagine my program needs input from the user at different times.假设我的程序需要用户在不同时间输入。 I want this input to prevent flushing the
cout
buffer.我希望此输入可以防止刷新
cout
缓冲区。 Can I set cin
and cout
on different stream buffers?我可以在不同的流缓冲区上设置
cin
和cout
吗?
Example in question: a program that reads two numbers in a line, n1 n2
, and depending on the first number being either 0
, 1
, or 2
:相关示例:一个程序读取一行中的两个数字
n1 n2
,并且取决于第一个数字是0
、 1
或2
:
n1 = 0
: writes the second number n2
to a vector v
n1 = 0
:将第二个数字n2
写入向量v
n1 = 1
: outputs v[n2]
in cout
n1 = 1
: 在cout
输出v[n2]
n1 = 2
: pop_back()
on v
n1 = 2
: v
上的pop_back()
The MWE is: 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;
}
Say I have this test input说我有这个测试输入
8
0 1
0 2
0 3
2
0 4
1 0
1 1
1 2
correct output should be正确的输出应该是
1
2
4
The program above yields outputs interspersed with the input lines instead.上面的程序产生的输出散布在输入行中。
But I would like them all printed together at end program, without using different means eg storing them in some container etc.但是我希望它们在最终程序中一起打印,而不使用不同的方法,例如将它们存储在某个容器中等。
So I think I should operate on the buffer, but how?所以我想我应该对缓冲区进行操作,但是如何操作呢?
You could write to your own std::stringstream
buffer, and then output that to std::cout
when you're ready.您可以写入自己的
std::stringstream
缓冲区,然后在准备好后将其输出到std::cout
。
MWE: 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();
}
No need to modify the buffer.无需修改缓冲区。 Instead of
cout << v[n2]
you can store v[n2]
in a second vector and print it out on the outside of the loop.您可以将
v[n2]
存储在第二个向量中并将其打印在循环的外部,而不是cout << v[n2]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.