Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use cin with a variable number of inputs?

Tags:

c++

I was in a programming competition yesterday and we had to read in input of the form

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

where the first line says how many inputs there are, and the next line contains that many inputs (and all inputs are integers).

I know if each line has the same number of inputs (say 3), we can write something like

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

But how do you do it when each line can have a different number of inputs?

like image 597
Jessica Avatar asked Aug 23 '13 17:08

Jessica


People also ask

Can CIN take multiple inputs?

Yes, you can input multiple items from cin , using exactly the syntax you describe.

Can CIN be used as a variable?

cin is a predefined variable that reads data from the keyboard with the extraction operator ( >> ).

How do you take unknown number inputs?

Using return value of cin to take unknown number of inputs in C++ Consider a problem where we need to take an unknown number of integer inputs. A typical solution is to run a loop and stop when a user enters a particular value.

How do I get infinite input in C++?

try this: int num; cout << "Enter numbers separated by a space" << endl; do { cin >> num; /* process num or use array or std::vector to store num for later use */ }while (true);


1 Answers

Here's a simple take using just standard libraries:

#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";
    }
}

See it live on Coliru: input

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

Output:

1 2 3 4 5 
6 7 8 9 10 11 12
like image 119
sehe Avatar answered Oct 14 '22 04:10

sehe