A more C++ish way would probably be to use std::getline
to read the line into a std::string
. Then put that string into an std::istringstream
, from which you then use std::istream_iterator
to fill the vector.
Perhaps something like
// Somewhere to put the text we read
std::string line;
// Read the actual text
std::getline(std::cin, line);
// A stream to parse the integers from
std::istringstream iss(line);
// Define the vector, initializing it from stream iterators
// This is a more succinct version of a loop which extracts (with `>>`)
// integers and pushes them into the vector
std::vector<int> vec(std::istream_iterator<int>(iss), std::istream_iterator<int>());
After this vec
is filled with integers from a single line of input.