2020-09-16 12:43:40
在C++中,可通过标准库fstream、sstream和string实现CSV文件的读写操作。以下是具体方法及注意事项:
一、读取CSV文件核心逻辑:逐行读取文件内容,按逗号分割字段。基本步骤:
示例代码:
#include <iostream>#include <fstream>#include <sstream>#include <vector>#include <string>void readCSV(const std::string& filename) { std::ifstream file(filename); std::string line, cell; while (std::getline(file, line)) { std::vector<std::string> row; std::stringstream ss(line); while (std::getline(ss, cell, ',')) { row.push_back(cell); } // 打印每行数据 for (const auto& item : row) { std::cout << item << " "; } std::cout << "n"; }}注意事项:
核心逻辑:将数据按逗号连接,每行末尾添加换行符。基本步骤:
示例代码:
#include <fstream>#include <vector>#include <string>void writeCSV(const std::string& filename, const std::vector<std::vector<std::string>>& data) { std::ofstream file(filename); for (const auto& row : data) { for (size_t i = 0; i < row.size(); ++i) { file << row[i]; if (i != row.size() - 1) file << ","; } file << "n"; }}注意事项:
1. 带引号字段的解析
fast-cpp-csv-parser:高性能解析,支持转义字符和类型转换。
csv.hpp:轻量级库,简化带引号字喊晌段的处理。
2. 大数据量优化
通过合理选择方法,可高效完成CSV文件的读写任务,同时兼顾代码简洁性与可靠性。