我提取了这段代码来解析一个CSV文件,但它没有读取前n-1行的第一个元素。我无法弄明白为什么,当我将数据复制到一个新的空文件并将其保存为CSV文件时,错误消失并且工作正常。以下是original(错误发生)和copied(错误未发生)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 :(得分:0)
您的原始文件中的新行以carriage return结尾,您的代码会读取该行中的最后一行,然后打印。所以第一行打印就像这样
1 2 3 4 5\r
然后打印空格,打印在行的开头,覆盖“1”。
您可以在调试器中轻松看到:)