Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read space separated numbers from console?

Tags:

c++

iostream

stl

I'm trying to do a simple task of reading space separated numbers from console into a vector<int>, but I'm not getting how to do this properly.

This is what I have done till now:

int n = 0;
vector<int> steps;
while(cin>>n)
{
    steps.push_back(n);
}

However, this requires the user to press an invalid character (such as a) to break the while loop. I don't want it.

As soon as user enters numbers like 0 2 3 4 5 and presses Enter I want the loop to be broken. I tried using istream_iterator and cin.getline also, but I couldn't get it working.

I don't know how many elements user will enter, hence I'm using vector.

Please suggest the correct way to do this.

like image 208
Asha Avatar asked Mar 31 '11 08:03

Asha


1 Answers

Use a getline combined with an istringstream to extract the numbers.

std::string input;
getline(cin, input);
std::istringstream iss(input);
int temp;
while(iss >> temp)
{
   yourvector.push_back(temp);
}
like image 148
jonsca Avatar answered Sep 20 '22 01:09

jonsca