12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-04 20:26:43
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在C++中读取CSV文件可以使用文件流操作符<<和>>,以及getline()函数。以下是一个简单的示例代码:#include <iostream>#include <fstream>#include <string>#include <vector>#i
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在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文件中的单元格以逗号分隔,如果使用其他分隔符,需要相应地修改上面的代码。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19