c++读取csv文件怎么存到二维数组中

   2024-10-13 5210
核心提示:可以使用以下代码来读取CSV文件并将其存储到二维数组中:#include iostream#include fstream#include sstream#include vectorint

可以使用以下代码来读取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来解析每行数据并存储到一个行向量中。最后,我们将每行向量添加到数据向量中。最后,我们遍历数据向量并打印数据。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号