1

こんばんは、次の問題があります。私は次のようにcsvファイルを解析しています:

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

私はこの方法でエントリを取得しています:

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

しかし、最後の行(;;)で問題が発生し、2つのエントリしか読み取れなかったため、3番目の空白のエントリを読み取る必要があります。どうすればいいですか?

4

1 に答える 1

2

まず、コードの問題を指摘する必要があります。iss最初の行を読み取ってから呼び出した後は失敗状態にwhile(getline(iss, entry, ';'))なっているため、すべての行を読み取った後、をリセットする必要がありますstringstream。失敗状態にある理由は、を呼び出した後、ストリームでファイルの終わりに到達するためですstd:getline(iss, entry, ';'))

あなたの質問の場合、簡単なオプションの1つは、何かが読み込まれたかどうかを確認すること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
}
于 2013-03-10T22:30:30.970 に答える