2016-08-17 184 views
0

我提取了這段代碼來解析CSV文件,但是它不讀取第一個n-1行的第一個元素。我無法弄清楚爲什麼,當我將數據複製到一個新的空文件並將其保存爲CSV文件時,錯誤消失並且工作正常。以下是original(發生錯誤)和copied(錯誤不會發生)CSV文件的鏈接。你能幫我解釋爲什麼會發生這種情況嗎?C++中的CSV解析器不讀取第一個元素

謝謝。

#include <boost/tokenizer.hpp> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <iostream> 
#include <cstdlib> 

int main(int argc, char** argv) 
{ 
    using namespace std; 

    if (argc != 2) 
    { 
     cerr << "Usage: " << argv[0] << " <csv file>" << endl; 
     return -1; 
    } 

    vector< vector<string> > csv_values; 

    fstream file(argv[1], ios::in); 

    if (file) 
    { 
     typedef boost::tokenizer< boost::char_separator<char> > Tokenizer; 
     boost::char_separator<char> sep(","); 
     string line; 

     while (getline(file, line)) 
     { 
      Tokenizer info(line, sep); // tokenize the line of data 
      vector<string> values; 

      for (Tokenizer::iterator it = info.begin(); it != info.end(); ++it) 
      { 
       // convert data into double value, and store 
       values.push_back(it->c_str()); 
      } 

      // store array of values 
      csv_values.push_back(values); 
     } 
    } 
    else 
    { 
     cerr << "Error: Unable to open file " << argv[1] << endl; 
     return -1; 
    } 

    // display results 
    cout.precision(1); 
    cout.setf(ios::fixed,ios::floatfield); 

    for (vector< vector<string> >::const_iterator it = csv_values.begin(); it != csv_values.end(); ++it) 
    { 

     const vector<string>& values = *it; 

     for (vector<string>::const_iterator it2 = values.begin(); it2 != values.end(); ++it2) 
     { 
      cout << *it2 << " "; 
     } 
     cout << endl; 
    } 
} 
+0

唯一的區別是複製文件末尾的空行。 – KIIV

回答

0

在原單文件的新線路用carriage return,其通過您的代碼與最後varible在線讀,然後印刷結束。所以第一行是這樣打印的

1 2 3 4 5\r 

然後你打印空間,它打印在行首,覆蓋「1」。

你可以很容易地看到,在調試器:)

+0

謝謝!這是我第一次聽說回車,現在我知道了! :) – vlavyb