c++stdistreamistringstream

istringstream skip next (n) word(s)


Is there a propper way in an isstrinstream to skip/ ignore the next, or even the next n words?

The possibility to read n times a variable seems to work, but is very clunky:

for (int i = 0; i < n; ++i) 
{
    std::string tmp;
    some_stream >> tmp;
}

std::istream::ignore doesn't seem to do the job, as only n letters are skipped.


Solution

  • It's clunky because it's not common enough to have gotten the appropriate attention to get a standard algorithm in place.

    {
        std::string tmp;
        for(size_t i = 0; i < number_of_words_to_skip; ++i) some_stream >> tmp;
    }
    

    You can make it fancier by creating a null receiver:

    std::copy_n(std::istream_iterator<std::string>(some_stream),
                number_of_words_to_skip,
                std::back_inserter(instance_of_something_that_does_not_do_anything));
    

    Since the std library is void of such a receiver and adding it for this one case is likely to cause more confusion than your original solution., I'd say that the idiomatic approach, Today, is just to make a loop like above.