How can I use cin just one time?

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

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

      

However, after entering my numbers and hitting enter, for example:

1 2 3 4 5

      

It puts numbers into a vector and then expects more input, meaning I have to enter Ctrl+Z

to exit the loop. How do I automatically exit the loop after receiving one line of integers so that I don't have to type Ctrl+Z

?

+3


source to share


2 answers


The easiest way to achieve this is to use a stream of lines:

#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 check the input, after the loop, you can do:

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

      

+9


source


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();
    }
}

      

0


source







All Articles