c++ getline and stringstream

22,520

If >> sees that there is nothing left in the stringstream, it will leave the variable untouched - so dx.out keeps its value from the last line. However, you can do

ss >> dx.in >> dx.name >> dx.id;
if (!(ss >> dx.out))
    dx.out = "";

because ss >> dx.out returns ss, and when a stream is converted to a bool (such as when it is used in an if condition), it returns false if the last read attempt failed.

Share:
22,520
wfmn17
Author by

wfmn17

Updated on May 05, 2020

Comments

  • wfmn17
    wfmn17 almost 4 years

    I'm trying to read in a file, which has 5 lines, and every line is 3-4 string long. Here's my input file:

    10:30 Hurley 1234567A 10:15
    10:45 Hurley 1234567A 11:30
    08:35 Jacob 1x1x1x1x1x
    08:35 Jacob 1x1x1x1x1x 08:10
    08:05 Jacob 1x1x1x1x1x
    08:45 Sayid 33332222 09:15
    

    And this is what I get:

    10:30 Hurley 1234567A   10:15
    10:45 Hurley 1234567A   11:30
    08:35 Jacob  1x1x1x1x1x 11:30
    08:35 Jacob  1x1x1x1x1x 08:10
    08:05 Jacob  1x1x1x1x1x 08:10
    08:45 Sayid  33332222   09:15
    

    This is my code:

    void enor::Read(status &sx,isle &dx,ifstream &x){
        string str;
        getline(x, str, '\n');
        stringstream ss;
        ss << str;
        ss >> dx.in >> dx.name >> dx.id >> dx.out;
        /*getline(x, str, '\n');
        x>>dx.in>>dx.name>>dx.id>>dx.out;*/
        if(x.fail())
            sx=abnorm;
        else
            sx=norm;
    }
    

    How can I read in the file without having the 3rd and 5th line filled with the 2nd and 4th line's time? I want the dx.out to be empty. Should I use another method, or is it possible to be done with stringstream?