uranix
uranix

Reputation: 686

stringstream goes to failed state if line is not whitespace terminated

I am trying to parse a file by reading it line-by-line and parsing each line using stringstream. Here's a simplified version of my code

#include <sstream>
#include <fstream>
#include <iostream>

using namespace std;

int main() {
    fstream f("input.txt", ios::in);
    stringstream ss;
    string line;
    while (getline(f, line)) {
        cout << "Got line `" << line << "'" << endl;
        ss.str(line);
        string prefix;
        ss >> prefix;
        cout << "Prefix: " << prefix << endl;
    }
    return 0;
}

In case of input.txt like (↲ used to denote newline)

a b↲
c d↲
e f↲

everything works as suggested, but for files like

a↲
c d↲
e f↲

stringstream goes to failed (not sure) state after a↲ line. It seems that stringstream expects the line to be whitespace terminated or similar. Sure i could manualy add a whitespace or linebreak. Anyway, I failed to find any info about this behaviour in stringstream manual.

So my question is why is this happening and how to properly resolve this problem.

Upvotes: 1

Views: 194

Answers (1)

David G
David G

Reputation: 96810

The line ss >> prefix reaches the EOF character when there's only token to be extracted. You have to clear the flag with ss.clear():

ss.clear();
ss.str(line);

Upvotes: 2

Related Questions