基本信息
源码名称:C++ 读取和写入CSV文件
源码大小:0.02M
文件格式:.zip
开发语言:C/C++
更新时间:2019-11-08
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

接受C 实现读取和写入文件

//#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;    
}