Shadow
Shadow

Reputation: 4006

How can I use cin only once?

I want to get multiple numbers from the user, in one line, and store it in a vector. This is how I am doing it:

vector<int> numbers;
int x;
while (cin >> x)
    numbers.push_back(x);

However, after entering my numbers and pressing enter, like so:

1 2 3 4 5

It puts the numbers in the vector, and then awaits more input, meaning I have to enter Ctrl+Z to exit the loop. How do I automatically exit the loop after getting the one line of integers, so that I don't have to enter Ctrl+Z?

Upvotes: 3

Views: 400

Answers (2)

P0W
P0W

Reputation: 47794

The simplest way to achieve this would be using a string stream :

#include <sstream>
//....

std::string str;
std::getline( std::cin, str ); // Get entire line as string
std::istringstream ss(str);

while ( ss >> x ) // Now grab the integers
    numbers.push_back(x); 

To validate the input, after loop you can do:

if( !ss.eof() )
{
   // Invalid Input, throw exception, etc
}

Upvotes: 9

Kastaneda
Kastaneda

Reputation: 749

while (std::cin.peek() != '\n') {
    std::cin >> x;
    numbers.push_back(x);
}

update

while (std::cin.peek() != '\n') {
    std::cin >> x;
    numbers.push_back(x);

    // workaround for problem from comment
    int tmp;
    while (!isdigit(tmp = std::cin.peek()) && tmp != '\n') {
      std::cin.get();
    }
}

Upvotes: 0

Related Questions