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?

5
  • 1
    I wouldn't use stringstream for this, just split each line at the semicolons. Commented Mar 10, 2013 at 22:16
  • Have a look at this question Commented Mar 10, 2013 at 22:17
  • I can't use <vector>, it's forbidden by evaluation computer. Commented Mar 10, 2013 at 22:21
  • Then what may you use? You can just replace the vector.push_back(...) with your do something Commented Mar 10, 2013 at 22:24
  • I can use only these: #include <iostream> #include <iomanip> #include <fstream> #include <sstream> #include <string> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <stdint.h> Commented Mar 10, 2013 at 22:25

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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: Okay, make sure you don't leave out any important code when posting a question though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.