2016-08-17 187 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