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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With