Search code examples
c++istringstream

How to read a word from std::istringstream without assigning to a tmp variable through >>?


I have a std::string line which contains a line of text read from a file. I then create a istringstream:

std::istringstream str(line);

to read this line. To get the first word, I do this:

std::string word;
str >> word;

Is there a way to get the word directly from str, without declaring the intermediate variable word?

For example, I would like to do something like:

if (str.get_next_word_directly() == "yes")
     do_something();

Solution

  • You have to use a named variable to do this; it is possible to extract into a temporary but then you have no way of identifying that temporary to call operator== on it.

    One option would be to wrap the extraction in a function, e.g.

    std::string get_word(std::istream& is)
    {
        std::string word;
        is >> word;
        return word;
    }
    

    and then you can write

    if( get_word(str) == "yes" )
    

    NB. There is a proposal for C++17 that would allow str.get_word() instead of get_word(str); but for now you're stuck with get_word(str).