1

Good evening, I've got the following problem. I am parsing csv file like this:

entry1;entry2;entry3
entry4;entry5;entry6
;;

I'm getting entries this way:

stringstream iss;
while(getline(file, string) {
iss << line;
     while(getline(iss, entry, ';') {
     /do something
     }
}

But I've got a problem with last row (;;) where I did read only 2 entries, I need to read the third blank entry. How can I do it?

Termininja
  • 6,620
  • 12
  • 48
  • 49
user2129659
  • 7
  • 1
  • 3

1 Answers1

2

First, I should point out a problem in the code, your iss is in the fail state after reading the first line and then calling while(getline(iss, entry, ';')), so after reading every line you need to reset the stringstream. The reason it is in the fail state is that the end of file is reached on the stream after calling std:getline(iss, entry, ';')).

For your question, one simple option is to simply check whether anything was read into entry, for example:

stringstream iss;
while(getline(file, line)) {
iss << line; // This line will fail if iss is in fail state
entry = ""; // Clear contents of entry
     while(getline(iss, entry, ';')) {
         // Do something
     }
     if(entry == "") // If this is true, nothing was read into entry
     { 
         // Nothing was read into entry so do something
         // This doesn't handle other cases though, so you need to think
         // about the logic for that
     }
     iss.clear(); // <-- Need to reset stream after each line
}
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • I've got iss.clear(); in my code byt I didn't paste it here. I've solved my problem this way: if ';' is on the end of the line, do something ;) SO thanks, my problem is solved. – user2129659 Mar 10 '13 at 22:45
  • @user2129659: Okay, make sure you don't leave out any important code when posting a question though. – Jesse Good Mar 10 '13 at 23:00