c++怎么读取csv文件中的数据

   2024-10-13 2990
核心提示:在C++中读取CSV文件中的数据通常需要使用文件流(ifstream)和字符串流(stringstream)来处理。以下是一个示例代码,演示如何读

在C++中读取CSV文件中的数据通常需要使用文件流(ifstream)和字符串流(stringstream)来处理。以下是一个示例代码,演示如何读取CSV文件中的数据:

#include <iostream>#include <fstream>#include <sstream>#include <vector>#include <string>int main() {    // 打开CSV文件    std::ifstream file("data.csv");    std::vector<std::vector<std::string>> data; // 用来存储CSV文件中的数据    // 逐行读取文件    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); // 将当前行数据存入data中    }    // 输出读取的数据    for (const auto& row : data) {        for (const auto& cell : row) {            std::cout << cell << " ";        }        std::cout << std::endl;    }    return 0;}

在这个示例中,我们首先打开了名为“data.csv”的CSV文件,并使用getline函数逐行读取文件内容。然后,在内部循环中,我们使用stringstream和getline函数来逐个单元格读取每行数据,并将其存储在二维向量data中。最后,我们遍历data向量,并输出读取的数据。

请注意,上面的示例假设CSV文件中的数据以逗号作为分隔符。如果CSV文件中使用其他分隔符,只需将getline函数的第三个参数改为相应的分隔符即可。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号