Search code examples
c++streamgetlinedefault-constructor

How to use stringstream constructor in getline?


Following up https://stackoverflow.com/a/1120224/390066.

Why can't I use

getline(stringstream(line),cell,','){}

instead of

stringstream lineStream(line); 
getline(lineStream,cell,','){}

?

update

I should have clarified that I want to use getline within a loop.

Furthermore, I should have also noted that my initial intention was to read a file line-by-line using getline and use the line from that in the new getline that would divide on ',', which is more intuitive imo.

From what I understood so far, getline is not designed for that because it takes a non-const input and gives const token; therefore, getline cannot be blindly recursed.


Solution

  • As show by @James Kanze you can.

    The question is do you really want to?
    The stream is destroyed at the end of the expression so you are only reading one cell from it.

    If we look at this in the context of the original question:
    i.e. You can not use that in a loop:

    std::string       line = /* Init */;
    std::stringstream lineStream(line); 
    
    std::string cell;
    while(std::getline(lineStream, cell, ','))
    {
        // Do stuff with cell.
    }
    

    If you place your code into this context it will not work as expected:

    std::string cell;
    while(std::getline(std::istringstream(line).flush(), cell, ','))
    {
        // Do stuff with cell.
    }
    

    As the expression inside the while() will be fully evaluated each time. So you go into an infinte loop reading the first cell continuously.