c++怎么读取csv文件中的数据

avatar
作者
筋斗云
阅读量:0

在C++中读取CSV文件中的数据通常需要使用文件流(ifstream)和字符串流(stringstream)来处理。以下是一个示例代码,演示如何读取CSV文件中的数据:

#include  #include  #include  #include  #include   int main() {     // 打开CSV文件     std::ifstream file("data.csv");      std::vector> data; // 用来存储CSV文件中的数据      // 逐行读取文件     std::string line;     while (std::getline(file, line)) {         std::vector row;         std::stringstream ss(line);         std::string cell;          // 逐个单元格读取数据         while (std::getline(ss, cell, ',')) {             row.push_back(cell);         }          data.push_back(row); // 将当前行数据存入data中     }      // 输出读取的数据     for (const auto& row : data) {         for (const auto& cell : row) {             std::cout << cell << " ";         }         std::cout << std::endl;     }      return 0; } 

在这个示例中,我们首先打开了名为“data.csv”的CSV文件,并使用getline函数逐行读取文件内容。然后,在内部循环中,我们使用stringstream和getline函数来逐个单元格读取每行数据,并将其存储在二维向量data中。最后,我们遍历data向量,并输出读取的数据。

请注意,上面的示例假设CSV文件中的数据以逗号作为分隔符。如果CSV文件中使用其他分隔符,只需将getline函数的第三个参数改为相应的分隔符即可。

    广告一刻

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