如何防止`std::cin`或`\n`刷新`std::cout`的缓冲区?

Gio*_*gre 0 c++ io iostream streambuf

让我们想象一下我的程序需要用户在不同时间输入。我希望这个输入可以防止刷新cout缓冲区。我可以在不同的流缓冲区上设置cin和吗?cout

相关示例:一个程序读取一行中的两个数字 , n1 n2,并且取决于第一个数字是0, 1, 或2

  • n1 = 0:将第二个数字写入n2向量v
  • n1 = 1:输出v[n2]cout
  • n1 = 2pop_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;
}
Run Code Online (Sandbox Code Playgroud)

假设我有这个测试输入

8
0 1
0 2
0 3
2
0 4
1 0
1 1
1 2
Run Code Online (Sandbox Code Playgroud)

正确的输出应该是

1
2
4
Run Code Online (Sandbox Code Playgroud)

上面的程序产生的输出散布在输入行中。

但我希望它们在最终程序中全部打印在一起,而不使用不同的方式,例如将它们存储在某个容器中等。

所以我想我应该对缓冲区进行操作,但是如何操作呢?

Elj*_*jay 6

您可以写入自己的std::stringstream缓冲区,然后std::cout在准备好时将其输出。

微量元素:

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