istringstream not outputting correct data

249 views Asked by At

I am having trouble getting istringstream to continue in while loop shown below. The data file is shown below also. I use getline from Input file to get the first line and put it in a istringstream lineStream. It passes through the while loop once, then it reads in the second line and goes back to the beginning of the loop and exits rather than continue through the loop. I have no clue why, if anyone could help I would thankful. EDIT: The reason I have this while loop condition is because the file may contain lines of erroneous data. Therefore, I want to make sure the line I am reading in has the proper form shown below in the data file.

while(lineStream >> id >> safety){//keeps scanning in xsections until there is no more xsection IDs

    while(lineStream >> concname){//scan in name of xsection
        xname = xname + " " +concname;
    }


    getline(InputFile, inputline);//go to next xsection line
    if(InputFile.good()){
        //make inputline into istringstream
        istringstream lineStream(inputline);
        if(lineStream.fail()){
            return false;
        }
    }
}

Data FILE

4   0.2  speedway and mountain
7   0.4 mountain and lee
6   0.5 mountain and santa
1

There are 1 answers

6
Cheers and hth. - Alf On BEST ANSWER

In the presented code, …

while(lineStream >> id >> safety){//keeps scanning in xsections until there is no more xsection IDs

    while(lineStream >> concname){//scan in name of xsection
        xname = xname + " " +concname;
    }

    getline(InputFile, inputline);//go to next xsection line
    if(InputFile.good()){
        //make inputline into istringstream
        istringstream lineStream(inputline);
        if(lineStream.fail()){
            return false;
        }
    }
}

… the inner declaration of lineStream declares a local object, which ceases to exist when the execution passes out of that block, and which doesn't affect the stream used in the outer loop.


One possible fix is to invert the code a little bit, like this:

while( getline(InputFile, inputline) )
{
    istringstream lineStream(inputline);

    if(lineStream >> id >> safety)
    {
        while(lineStream >> concname)
        {
            xname = xname + " " +concname;
        }
        // Do something with the collected info for this line
    }
}