如何在C ++中读取和操作CSV文件数据? [英] How can I read and manipulate CSV file data in C++?

查看:533
本文介绍了如何在C ++中读取和操作CSV文件数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相当不说自明,我试过google,得到了很多可怕的expertsexchange,我在这里搜索也没有效果。在线教程或示例是最好的。

Pretty self-explanatory, I tried google and got a lot of the dreaded expertsexchange, I searched here as well to no avail. An online tutorial or example would be best. Thanks guys.

推荐答案

如果你真正做的是处理一个CSV文件本身,尼尔森的答案是有道理的。然而,我的怀疑是,CSV只是一个人工的你解决的问题。在C ++中,这可能意味着你有这样的数据模型:

If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model:

struct Customer {
    int id;
    std::string first_name;
    std::string last_name;
    struct {
        std::string street;
        std::string unit;
    } address;
    char state[2];
    int zip;
};

因此,当您使用数据集合时, $ c> std :: vector< Customer> 或 std :: set< Customer>

Thus, when you're working with a collection of data, it makes sense to have std::vector<Customer> or std::set<Customer>.

考虑到这一点,将您的CSV处理视为两个操作:

With that in mind, think of your CSV handling as two operations:

// if you wanted to go nuts, you could use a forward iterator concept for both of these
class CSVReader {
public:
    CSVReader(const std::string &inputFile);
    bool hasNextLine();
    void readNextLine(std::vector<std::string> &fields);
private:
    /* secrets */
};
class CSVWriter {
public:
    CSVWriter(const std::string &outputFile);
    void writeNextLine(const std::vector<std::string> &fields);
private:
    /* more secrets */
};
void readCustomers(CSVReader &reader, std::vector<Customer> &customers);
void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers);

一次读取和写入一行,而不是保持一个完整的文件本身。有以下几个明显的好处:

Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits:


  1. 您的数据以对您的问题(客户)有意义的形式表示,而不是当前

  2. 您可以轻松地为其他数据格式添加适配器,例如批量SQL导入/导出,Excel / OO电子表格文件,甚至是HTML c>

  3. 您的内存占用可能会更小(取决于相对 sizeof(Customer)与单行中的字节数)。

  4. CSVReader CSVWriter 可以重复用作内存模型(如Nelson的)的基础,而不会失去性能或功能。反之亦然。

  1. Your data is represented in a form that makes sense for your problem (customers), rather than the current solution (CSV files).
  2. You can trivially add adapters for other data formats, such as bulk SQL import/export, Excel/OO spreadsheet files, or even an HTML <table> rendering.
  3. Your memory footprint is likely to be smaller (depends on relative sizeof(Customer) vs. the number of bytes in a single row).
  4. CSVReader and CSVWriter can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.

这篇关于如何在C ++中读取和操作CSV文件数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆