c++ - How can I use cin only once? -



c++ - How can I use cin only once? -

i want multiple numbers user, in 1 line, , store in vector. how doing it:

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

however, after entering numbers , pressing enter, so:

1 2 3 4 5

it puts numbers in vector, , awaits more input, meaning have come in ctrl+z exit loop. how automatically exit loop after getting 1 line of integers, don't have come in ctrl+z?

the simplest way accomplish using string stream :

#include <sstream> //.... std::string str; std::getline( std::cin, str ); // entire line string std::istringstream ss(str); while ( ss >> x ) // grab integers numbers.push_back(x);

to validate input, after loop can do:

if( !ss.eof() ) { // invalid input, throw exception, etc }

c++

Comments

Popular posts from this blog

maven fortify plugin : Unable to load build session with ID XXXXX .. See log file for more details -

c# - Primavera WebServices does not return any data -

android - Display emoji panel with genymotion - keyboard/touch input? -