How to cin values into a vector

As is, you’re only reading in a single integer and pushing it into your vector. Since you probably want to store several integers, you need a loop. E.g., replace

cin >> input;
V.push_back(input);

with

while (cin >> input)
    V.push_back(input);

What this does is continually pull in ints from cin for as long as there is input to grab; the loop continues until cin finds EOF or tries to input a non-integer value. The alternative is to use a sentinel value, though this prevents you from actually inputting that value. Ex:

while ((cin >> input) && input != 9999)
    V.push_back(input);

will read until you try to input 9999 (or any of the other states that render cin invalid), at which point the loop will terminate.

Leave a Comment