C++读取CSV文件保存到二维数组

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
auto read_csv(const char *filepath) {
    // 二维字符串向量,用于存储CSV数据
    std::vector<std::vector<std::string>> data;

    // 打开CSV文件
    std::ifstream file(filepath);
    if (!file.is_open()) {
        throw std::runtime_error("Failed to open file: " + std::string(filepath));
    }

    // 逐行读取CSV文件内容并存储到二维数组中
    std::string line;
    while (std::getline(file, line)) {
        std::stringstream ss(line);
        std::vector<std::string> row;
        std::string cell;
        while (std::getline(ss, cell, ',')) {
            row.push_back(cell);
        }
        data.push_back(row);
    }
    file.close();
    return data;
}
template <typename T> 
void print_array2d(T data) {
    for (const auto &row : data) {
        for (const auto &cell : row) {
            std::cout << cell << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    auto arr2d = read_csv("./test/md_data/tick_rb2410.csv");
    print_array2d(arr2d);
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将一个以逗号分隔的 CSV 格式文件读取二维数组中,你可以使用 C++文件输入流和字符串分割操作。 下面是一个示例代码,展示如何实现这个功能: ```cpp #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> std::vector<std::vector<std::string>> readCSV(const std::string& filename) { std::ifstream file(filename); std::vector<std::vector<std::string>> data; if (file) { std::string line; while (std::getline(file, line)) { std::vector<std::string> row; std::stringstream lineStream(line); std::string cell; while (std::getline(lineStream, cell, ',')) { row.push_back(cell); } data.push_back(row); } file.close(); } else { std::cout << "Failed to open file: " << filename << std::endl; } return data; } int main() { std::string filename = "path/to/csv/file.csv"; std::vector<std::vector<std::string>> data = readCSV(filename); // 输出读取到的二维数组 for (const auto& row : data) { for (const auto& cell : row) { std::cout << cell << " "; } std::cout << std::endl; } return 0; } ``` 在这个例子中,我们定义了一个 `readCSV()` 函数,该函数接受 CSV 文件的路径作为输入参数,并返回一个二维字符串向量表示的数据。 在 `readCSV()` 函数中,我们首先打开文件,然后逐行读取文件内容。对每一行,我们使用 `std::getline()` 函数和逗号作为分隔符来分割字符串,将每个单元格的内容存储到一个字符串向量中。最后,将每一行的字符串向量添加到二维数据向量中。 在 `main()` 函数中,我们调用 `readCSV()` 函数来读取 CSV 文件,并将结果存储在 `data` 变量中。然后,我们遍历二维数据向量并打印出每个单元格的内容。 记得在使用这段代码时,要包含 `<iostream>`、`<fstream>`、`<sstream>` 和 `<vector>` 头文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值