c++stream

std::stringstream - discard a value


Sometimes I use std::stringstream to parse a text file, e.g.

8 9
100 1002 3.345
100 102  2.345


std::stringstream ss(file);
int unused1, unused2, first_useful_value;
ss >> unused1 >> unused2;
ss >> first_useful_value >> ...

now suppose that the first line, i.e.

8 9 

are useless values to me and I just need to discard them. I might consider the entire line useless or I might consider some of those values useless.

My question is: is there any way to discard a value of a given type without having to declare useless variables on the stack (either wasteful and less readable)?


Solution

  • You can use std::stringstream::ignore with delimeter \n to skip the first line as follows:

      ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    

    LIVE DEMO

    or use as delimiter space or what ever separates your values to discard one at a time:

    ss.ignore(std::numeric_limits<std::streamsize>::max(), ' '); // delimiter is space
    ss.ignore(std::numeric_limits<std::streamsize>::max(), ','); // delimeter is comma
    

    LIVE DEMO