C++对csv文件的读写

//#include <opencv2\opencv.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream> // 用于读写存储在内存中的string对象

int main(void)
{
    // 制作CSV文件
    /* Name,age,height
     * Tom,21,172.8
     * John,25,189.5
     */
     std::ofstream outFile;
     outFile.open("./csvTest.csv", std::ios::out);
     outFile << "Name" << "," << "age" << "," << "height" << std::endl;
     outFile << "Tom" << "," << 21 << "," << 172.8 << std::endl;
     outFile << "John" << "," << 25 << "," << 189.5 << std::endl;
     outFile.close();

     // 读取CSV文件
     struct CSVDATA {
      std::string name;
      int age;
      double height;
     };
     std::ifstream inFile("./csvTest.csv", std::ios::in);
     std::string lineStr;
     std::vector<struct CSVDATA> csvData;
     std::getline(inFile, lineStr); // 跳过第一行(非数据区域)
     while (std::getline(inFile, lineStr)) {
          std::stringstream ss(lineStr); // string数据流化
          std::string str;
          struct CSVDATA csvdata;
          std::getline(ss, str, ','); // 获取 Name
          csvdata.name = str;
          std::getline(ss, str, ','); // 获取 age
          csvdata.age = std::stoi(str);
          std::getline(ss, str, ','); // 获取 height
          csvdata.height = std::stod(str);

          csvData.push_back(csvdata);
     }
     // 显示读取的数据
     for (int i = 0; i < csvData.size(); i++ ) {
          std::cout << csvData[i].name << "," << csvData[i].age << "," << csvData[i].height << std::endl;
     }

     getchar();
     return 0;    
}
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值