parsing csv via C++

2019-08-13 19:08发布

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?

标签: c++ parsing csv
1条回答
在下西门庆
2楼-- · 2019-08-13 19:38

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
}
查看更多
登录 后发表回答