温馨提示×

C++中怎么读取CSV文件

c++
小亿
106
2024-04-15 18:13:09
栏目: 编程语言

在C++中读取CSV文件可以使用文件流操作符<<>>,以及getline()函数。以下是一个简单的示例代码:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

int main() {
    std::ifstream file("data.csv");
    std::vector<std::vector<std::string>> data;

    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            std::vector<std::string> row;
            std::stringstream ss(line);
            std::string cell;

            while (std::getline(ss, cell, ',')) {
                row.push_back(cell);
            }

            data.push_back(row);
        }

        file.close();
        
        // 输出CSV数据
        for (const auto& row : data) {
            for (const auto& cell : row) {
                std::cout << cell << " ";
            }
            std::cout << std::endl;
        }
    } else {
        std::cout << "Failed to open file." << std::endl;
    }

    return 0;
}

在这个示例中,我们首先打开名为"data.csv"的CSV文件,然后使用getline()函数逐行读取文件内容。对于每一行,我们使用stringstream对象解析每个单元格,并将其存储在一个vector<string>中。最后,我们将每行数据存储在一个vector<vector<string>>中,其中每个向量代表一行数据。最后,我们遍历这个二维向量并输出CSV数据。

注意:这里假设CSV文件中的单元格以逗号分隔,如果使用其他分隔符,需要相应地修改上面的代码。

0