It is very straightforward. All you need to do is perform the extraction as the condition:
while (i < MAX_SIZE && std::cin >> x[i++])
if the extraction fails for any reason (no more characters left, invalid input, etc.) the loop will terminate and the failure will be represented in the stream state of the input stream.
Considering best practices, you shouldn't be using static C-arrays. You should be using the compile-time container std::array<T, N>
(or std::vector<T>
if the former is not supported).
Here is an example using std::vector
. It also utilizes iterators which does away with having to explicitly create a copy of the input:
std::vector<int> v{ std::istream_iterator<int>{std::cin},
std::istream_iterator<int>{}};