c++读取csv文件怎么存到二维数组中
导读:可以使用以下代码来读取CSV文件并将其存储到二维数组中: #include <iostream> #include <fstream> #include <sstream> #include <ve...
可以使用以下代码来读取CSV文件并将其存储到二维数组中:
#include <
iostream>
#include <
fstream>
#include <
sstream>
#include <
vector>
int main() {
// Open the CSV file
std::ifstream file("data.csv");
// Check if the file is open
if (!file.is_open()) {
std::cerr <
<
"Could not open file" <
<
std::endl;
return 1;
}
// Create a two-dimensional vector to store the CSV data
std::vector<
std::vector<
std::string>
>
data;
// Read the file line by line
std::string line;
while (std::getline(file, line)) {
// Create a stringstream from the line
std::stringstream ss(line);
std::vector<
std::string>
row;
// Read each value from the stringstream and add it to the row vector
std::string value;
while (std::getline(ss, value, ',')) {
row.push_back(value);
}
// Add the row vector to the data vector
data.push_back(row);
}
// Print the data
for (const auto&
row : data) {
for (const auto&
value : row) {
std::cout <
<
value <
<
" ";
}
std::cout <
<
std::endl;
}
// Close the file
file.close();
return 0;
}
在上面的代码中,我们首先打开了一个名为"data.csv"的CSV文件。然后我们创建了一个二维vector来存储CSV数据。我们逐行读取文件,并使用stringstream来解析每行数据并存储到一个行向量中。最后,我们将每行向量添加到数据向量中。最后,我们遍历数据向量并打印数据。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c++读取csv文件怎么存到二维数组中
本文地址: https://pptw.com/jishu/681231.html