Can't output my whole file, premature exit by inputFile.eof()

63 views Asked by At
if(inputFile.is_open()){
        while(!inputFile.eof()){
            getline(inputFile, line);
            ss << line;
                while(ss){
                ss >> key;
                cout << key << " ";
                lineSet.insert(lineNumber);
                concordance[key] = lineSet;
            }
            lineNumber++;
        }   
    }

For some reason, the while loop is kicking out after the first iteration and only displays the first sentence of my input file. The rest of the code works fine, I just can't figure out why it thinks the file has ended after the first iteration.

Thanks

1

There are 1 answers

0
M.M On BEST ANSWER

Firstly you should be reading the file without using eof , as πάντα ῥεῖ notes (see here for explanation):

while( getline(inputFile, line) )
{
    // process the line
}

Note that the preceding if is not necessary either.

The main problem , assuming ss is a stringstream you defined earlier, comes from the logic:

ss << line;
while(ss){
    // stuff
}

The while loop here only exits when ss fails. But you never reset ss to be in a good state. So although your outer loop does read every line of the file, all of the lines after the first line never generate any output.

Instead you need to reset the stringstream each time:

ss.clear();
ss.str(line);
while (ss) {
    // stuff
}