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

时间:2013-08-23 17:42:21

标签: c++

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

n
a1 a2 ... an
m
b1 b2 ... bm
...

其中第一行表示有多少输入,下一行包含许多输入(所有输入都是整数)。

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

的内容
while (true) {
    cin >> a1 >> a2 >> a3;
    if (end of file)
        break;
}

但是当每一行可以有不同数量的输入时你怎么做?

7 个答案:

答案 0 :(得分: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";
    }
}

查看 live on Coliru :输入

5
1 2 3 4 5
7 
6 7 8 9 10 11 12

输出:

1 2 3 4 5 
6 7 8 9 10 11 12

答案 1 :(得分:2)

你可以这样做

#include<vector>
...
...
std::vector<sometype> a;
sometype b;
std::cin >> b;
while(std::cin)
{
 a.push_back(b);
 std::cin >> b;
}

您可以输入任意数量的项目,并在完成后发送EOF信号。

答案 2 :(得分:1)

您的算法将如下所示:

1. read the 'number' of inputs, say n1
2. set up a loop to read the n1 inputs
3. check if the user has more inputs to give
   if YES repeat the steps 1,2 and 3 till all inputs are taken and stored.
   else move on...

您可以使用for或while循环并将输入存储到数组中。

希望这有帮助!

答案 3 :(得分:1)

因为人们在抱怨我的第一个回答是“简单的”,这是使用Boost Spirit的正确版本:

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

int main()
{
    typedef std::vector<std::vector<double>> data_t;
    typedef boost::spirit::istream_iterator It;

    std::cin.unsetf(std::ios::skipws);
    It first(std::cin), last;

    bool ok;
    data_t contents;

    {
        using namespace boost::spirit::qi;
        static rule<It, data_t(),                        blank_type, locals<int>> file;
        static rule<It, std::vector<double>(int number), blank_type>              row;

        _a_type number; // friendly alias

        file %= -(omit [int_[number=_1]] > eol > row(number)) % eol;
        row   = repeat(_r1) [ double_ ];

        ok = phrase_parse(first, last, file, blank, contents);
    }

    if (ok) for (auto& row : contents)
    {
        std::copy(row.begin(), row.end(), std::ostream_iterator<double>(std::cout," "));
        std::cout << "\n";
    }

    if (first!=last)
        std::cout << "Warning: end of file not reached, remaining unparsed: '" << std::string(first, last) << "'\n";
}

显然远远优于

  • 它使用的包含行数少得多:)
  • 编译需要大约10倍(没有优化),优化需要16%的时间
  • 它需要大约5年的元编程学习才能理解它(开玩笑,精神文档/教程非常好)
  • 严肃的说法:它更灵活

    • 可以扩展为解析其他结构元素,更复杂
    • 可以动态实现语义
    • 将正确解析NaN和+/-无穷大

同时查看 Live on Coliru

答案 4 :(得分:1)

鉴于您指定的格式,我会这样做。

for (int n; std::cin >> n; )
{
    if (n == 0)     // Test for end of input
        break;

    for (int i = 0; i != n; ++i)
    {
        int x;
        std::cin >> x;
        if (!std::cin)
            break;

        // Valid input x. Now do something with x like
        // v.push_back(x) where v is some vector of ints
    }
}

// Did we succeed?
if (!std::cin)
{
    // Something went bad.
    std::cerr << "Error reading input" << std::endl;

    return EXIT_FAILURE;
}

答案 5 :(得分:0)

简单,使用for循环和数组。

int a[MAX]; // programming problems usually specify a max size
for(i=0;i<n;i++)
cin>>a[i];

答案 6 :(得分:0)

使用数组和动态内存分配的简单解决方案,用于获取预定义类型的可变数量的输入。

#include<iostream>
using namespace std;

int main(){
int n;
cout<<"Enter the number of elements"<<endl;
cin>>n;
int *c=new int[n];
for(int k=0;k<n;k++)
    cin>>c[k];
}