2013-03-10 65 views
1

晚上好,我遇到了以下問題。我解析CSV文件是這樣的:通過C++解析csv

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

我得到的條目是這樣的:

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

但我得到了與最後一排(;;),我也只有2讀取問題條目,我需要讀取第三個空白條目。我該怎麼做?

+1

我不會用這個'stringstream',只是在分號分開的每一行。 – 2013-03-10 22:16:15

+0

看看[這個問題](http://stackoverflow.com/questions/1120140/csv-parser-in-c?rq=1) – 2013-03-10 22:17:16

+0

我不能使用,它被評估計算機禁止。 – user2129659 2013-03-10 22:21:31

回答

2

首先,我應該指出代碼存在問題,您的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 
} 
+0

我有iss.clear();在我的代碼中,我沒有粘貼在這裏。我已經用這種方法解決了我的問題:if';'是在行的末尾,做點什麼;)謝謝,我的問題解決了。 – user2129659 2013-03-10 22:45:32

+0

@ user2129659:好的,確保在發佈問題時不要忽略任何重要的代碼。 – 2013-03-10 23:00:52