在C++中,要讀寫CSV文件可以使用標(biāo)準(zhǔn)庫中的fstream庫。下面是一個簡單的示例代碼:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main() {
std::ofstream outfile("data.csv");
if (!outfile.is_open()) {
std::cerr << "Error opening file." << std::endl;
return 1;
}
outfile << "Name,Age,Score" << std::endl;
outfile << "Alice,25,90" << std::endl;
outfile << "Bob,30,85" << std::endl;
outfile.close();
std::ifstream infile("data.csv");
if (!infile.is_open()) {
std::cerr << "Error opening file." << std::endl;
return 1;
}
std::string line;
std::vector<std::vector<std::string>> data;
while (std::getline(infile, line)) {
std::stringstream ss(line);
std::vector<std::string> row;
std::string cell;
while (std::getline(ss, cell, ',')) {
row.push_back(cell);
}
data.push_back(row);
}
infile.close();
for (const auto& row : data) {
for (const auto& cell : row) {
std::cout << cell << " ";
}
std::cout << std::endl;
}
return 0;
}
在上面的代碼中,首先我們創(chuàng)建了一個名為"data.csv"的CSV文件,并向文件中寫入了一些數(shù)據(jù)。然后我們再次打開文件并讀取數(shù)據(jù),將數(shù)據(jù)存儲在一個二維vector中,最后打印出數(shù)據(jù)內(nèi)容。