如何在 C++ 中读取和操作 CSV 文件数据?

2021-12-09 00:00:00 csv c++

不言自明,我试过谷歌并得到了很多可怕的专家交流,我也在这里搜索无济于事.最好是在线教程或示例.谢谢各位.

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 文件本身,那么 Nelson 的回答是有道理的.但是,我怀疑 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;
};

因此,当您处理一组数据时,使用 std::vectorstd::set 是有意义的.

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. 您的数据以对您的问题(客户)有意义的形式表示,而不是当前的解决方案(CSV 文件).
  2. 您可以轻松地为其他数据格式添加适配器,例如批量 SQL 导入/导出、Excel/OO 电子表格文件,甚至 HTML 渲染.
  3. 您的内存占用可能更小(取决于相对 sizeof(Customer) 与单行中的字节数).
  4. CSVReaderCSVWriter 可以作为内存模型(例如 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.

    相关文章