[英]CSV parser in C++ doesn't read the first element
我提取了這段代碼來解析CSV文件,但是它沒有讀取前n-1行的第一個元素。 我不知道為什么,當我將數據復制到一個新的空文件並將其另存為CSV文件時,錯誤消失了,並且可以正常工作。 這是原始 (發生錯誤)和復制 (沒有發生錯誤)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;
}
}
原始文件中的新行以回車結尾,該代碼由行中的最后一個變量讀取,然后打印。 所以第一行像這樣打印
1 2 3 4 5\r
然后打印空格,該空格打印在該行的開頭,覆蓋“ 1”。
您可以在調試器中輕松看到它:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.