C++中怎么读取CSV文件


在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文件中的单元格以逗号分隔,如果使用其他分隔符,需要相应地修改上面的代码。


上一篇:PHP中ReactPHP库的作用有哪些

下一篇:Android中怎么用ScrollView实现滚动效果


c++
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器