如何使用可变数量输入的cin?

Jes*_*ica 5 c++

我昨天参加了一个编程竞赛,我们不得不阅读表格的输入

n
a1 a2 ... an
m
b1 b2 ... bm
...
Run Code Online (Sandbox Code Playgroud)

第一行显示有多少输入,下一行包含许多输入(所有输入都是整数).

我知道如果每一行都有相同数量的输入(比如3),我们可以写出类似的东西

while (true) {
    cin >> a1 >> a2 >> a3;
    if (end of file)
        break;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果每条线可以有不同数量的输入,你怎么做?

seh*_*ehe 7

以下是使用标准库的简单方法:

#include <vector>       // for vector
#include <iostream>     // for cout/cin, streamsize
#include <sstream>      // for istringstream
#include <algorithm>    // for copy, copy_n
#include <iterator>     // for istream_iterator<>, ostream_iterator<>
#include <limits>       // for numeric_limits

int main()
{
    std::vector<std::vector<double>> contents;

    int number;
    while (std::cin >> number)
    {
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip eol
        std::string line;
        std::getline(std::cin, line);
        if (std::cin)
        {
            contents.emplace_back(number);
            std::istringstream iss(line);
            std::copy_n(std::istream_iterator<double>(iss), number, contents.back().begin());
        }
        else
        {
            return 255;
        }
    }

    if (!std::cin.eof())
        std::cout << "Warning: end of file not reached\n";

    for (auto& row : contents)
    {
        std::copy(row.begin(), row.end(), std::ostream_iterator<double>(std::cout," "));
        std::cout << "\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

在Coliru上看到它:输入

5
1 2 3 4 5
7 
6 7 8 9 10 11 12
Run Code Online (Sandbox Code Playgroud)

输出:

1 2 3 4 5 
6 7 8 9 10 11 12
Run Code Online (Sandbox Code Playgroud)