0

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

imex
  • 1
  • 5
    *learning C++ by solving competitive programming challenges* - It's the worst possible way to learn C++. Most "competitive programming" websites promote extremely bad code examples and programming styles. Prefer a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Evg Mar 13 '22 at 19:10
  • Are you familiar with `for` loops? – Beta Mar 13 '22 at 19:14
  • @Beta Yes, I have okay-ish Java and Python knowledge, so I am familiar with programming in general. – imex Mar 13 '22 at 19:53
  • @Evg I am doing it to familiarize myself with the overall syntax/"feel" of it, as I prefer to try things myself before reading up thorough examples to see what I need to improve and expand my understanding upon. Either way, I appreciate the link, I will definitely look into some! – imex Mar 13 '22 at 19:53
  • What's wrong with a for loop? – Michaël Roy Mar 14 '22 at 02:30
  • @good look is right. Competitive programming challenges is not how you learn a language. It's how one demonstrates mastery over a language, meaning one should learn the olanguage before doing competitive programming. – Michaël Roy Mar 14 '22 at 02:35

1 Answers1

0

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;
    }
}
Chris
  • 26,361
  • 5
  • 21
  • 42