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
Post a Comment