我提取了这段代码来解析一个 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;
}
}