通过C解析CSV ++(parsing csv via C++)

2019-10-17 19:13发布

晚上好,我有以下问题。 我解析这样的csv文件:

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

我得到的条目是这样的:

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

但我得到了与最后一排(;;),我也只读2项问题,我需要阅读的第三个空白项 。 我该怎么做?

Answer 1:

首先,我要在代码中指出一个问题,你的iss在故障状态下阅读的第一行,然后调用后while(getline(iss, entry, ';'))所以阅读每一行之后,你需要重新设置该stringstream 。 究其原因是在故障状态是在流到达文件的末尾呼吁后std:getline(iss, entry, ';'))

对于你的问题,一个简单的选择是简单地检查是否任何被读入entry ,例如:

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
}


文章来源: parsing csv via C++
标签: c++ parsing csv