c++如何读取csv
时间: 2024-12-26 11:07:04 浏览: 15
在C++中读取CSV文件,你可以使用一些第三方库如`csv-parser`, `picojson`, 或者直接操作文件流。这里简单介绍一种基于标准库的逐行解析方法:
```cpp
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
std::vector<std::vector<std::string>> read_csv(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
throw std::runtime_error("Failed to open the CSV file.");
}
std::vector<std::vector<std::string>> data;
std::string line;
while (std::getline(file, line)) {
std::stringstream ss(line);
std::vector<std::string> row;
std::string field;
while (std::getline(ss, field, ',')) { // 分割逗号
row.push_back(field);
}
data.push_back(row); // 将一行数据添加到结果列表
}
file.close();
return data;
}
// 使用示例
int main() {
try {
auto csv_data = read_csv("example.csv");
for (const auto &row : csv_data) {
for (const auto &field : row) {
std::cout << field << " ";
}
std::cout << "\n";
}
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
}
return 0;
}
```
在这个例子中,我们首先打开文件,然后逐行读取,每行数据通过逗号分割成一个个字段,并存储在一个二维字符串向量中。注意这只是一个基本的读取方式,实际处理可能需要考虑编码、错误处理等问题。
阅读全文
相关推荐















