Search code examples
stlistreamc++

Easiest way to get words of one line from istream into a vector?


istream has the >> operator, but it skips new lines like it skips whitespace. How can I get a list of all the words in 1 line only, into a vector (or anything else that's convenient to use)?


Solution

  • One possibility (though considerably more verbose than I'd like) is:

    std::string temp;
    std::getline(your_istream, temp);
    
    std::istringstream buffer(temp);
    std::vector<std::string> words((std::istream_iterator<std::string>(buffer)),
                                    std::istream_iterator<std::string>());