How to read numbers separated by a space from the console?

I am trying to accomplish the simple task of reading space-separated numbers from the console in vector<int> , but I do not understand how to do this correctly.

This is what I have done so far:

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

However, this requires the user to click an invalid character (e.g. a ) to break the while . I do not want it.

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

I don’t know how many elements the user enters, so I use vector .

Please suggest the right way to do this.

+7
source share
5 answers

Use getline in conjunction with istringstream to extract numbers.

 std::string input; getline(cin, input); std::istringstream iss(input); int temp; while(iss >> temp) { yourvector.push_back(temp); } 
+11
source

To clarify the answer to jonsca, there is one possibility here, assuming the user correctly enters valid integers:

 string input; getline(cin, input); istringstream parser(input); vector<int> numbers; numbers.insert(numbers.begin(), istream_iterator<int>(parser), istream_iterator<int>()); 

This will correctly read and parse a valid string of integers from cin . Note that this uses the free getline function, which works with std::string s, and not istream::getline , which works with C-style strings.

+7
source

This code should help you, it reads a line of the line and then iterates over it, selecting all the numbers.

 #include <iostream> #include <sstream> #include <string> int main() { std::string line; std::getline(std::cin, line); std::istringstream in(line, std::istringstream::in); int n; vector<int> v; while (in >> n) { v.push_back(n); } return 0; } 
+1
source

Ask the user after each number or pre-calculate the number and loop. Not a great idea, but I have seen this in many applications.

+1
source

It may also be useful to know that you can stimulate EOF - press "ctrl-z" (only windows, unix-like systems use ctrl-d) on the command line after you are done with your inputs. Should help you when you are testing small programs like this - without entering an invalid character.

+1
source

All Articles