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

avatar
作者
猴君
阅读量:0

可以使用以下代码来读取CSV文件并将其存储到二维数组中:

#include  #include  #include  #include   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> 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 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来解析每行数据并存储到一个行向量中。最后,我们将每行向量添加到数据向量中。最后,我们遍历数据向量并打印数据。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!