【问题标题】:CSV parser in C++ doesn't read the first elementC++ 中的 CSV 解析器不读取第一个元素
【发布时间】:2016-08-17 16:50:18
【问题描述】:

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

【问题讨论】:

  • 唯一的区别是复制文件末尾的空行。

标签: c++ csv boost-tokenizer


【解决方案1】:

原始文件中的新行以carriage return 结尾,您的代码使用该行中的最后一个变量读取它,然后打印。所以第一行是这样打印的

1 2 3 4 5\r

然后你打印空格,它打印在行首,覆盖“1”。

你可以很容易地在调试器中看到:)

【讨论】:

  • 谢谢!这是我第一次听说回车,现在我知道了! :)
猜你喜欢
  • 2014-05-03
  • 2016-11-24
  • 2021-12-11
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2012-06-28
  • 2016-02-06
  • 2020-09-20
相关资源
最近更新 更多