'Reading N elements in one line in C++

I have recently started to pick up learning C++ by solving competitive programming challenges and thelike, but I have run into an issue; is there any way to read an unknown/changing amount of elements in one line?

For example, if I wanted to read only one element in a line, I would do:

cin >> x;

For 2 elements:

cin >> x >> y;

etc., but is there any way to read a changing amount of these? Say I am given a number N that represents the amount of elements in one line I would have to read, is there any neat way to go about this? Thanks in advance



Solution 1:[1]

You could overload the >> operator for std::array. Using templates, the number of elements to be read in is read from the size of the array passed in.

#include <array>
#include <iostream>

template <typename T, std::size_t N>
std::istream& operator>>(std::istream& in, std::array<T, N>& arr) {
    for (std::size_t i = 0; i < N; ++i) {
        in >> arr[i];
    }

    return in;
}

int main() {
    std::array<int, 9> arr;

    std::cin >> arr;

    for (auto i : arr) {
        std::cout << i << std::endl;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris