csv文件其实就是文本文件,每行字段用逗号分隔。项目需要对csv文件进行数据操作,故搜到了一个比较好用的方案,并做了一定程度的修改,代码如下:

编译环境

系统环境:

patten@patten-hp:~$ sudo lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 16.04.6 LTS
Release:	16.04
Codename:	xenial
patten@patten-hp:~$

IDE环境:Visual Studio Code,Version: 1.38.1

代码示例

//collide.cpp

#include <fstream>  //定义读写已命名文件的类型
#include <iostream>
#include <sstream>  //多定义的类型则用于读写存储在内存中的string对象
#include <vector>

using namespace std;

int main() {
  //写文件
  ofstream outFile;

  //输出文件流(输出到文件)
  //你的文件路径如果文件不存在,可以自动创建,打开模式可省略
  outFile.open("/home/patten/workspace/others/data1.csv", ios::out);
  outFile << "name" << ',' << "age"
          << ","
          << "hobby" << endl;
  outFile << "xiaoming" << ',' << 18 << ","
          << "music" << endl;
  outFile << "Mike" << ',' << 21 << ","
          << "football" << endl;
  outFile << "Tom" << ',' << 23 << ","
          << "basketball" << endl;

  //读文件
  // inFile来自fstream,ifstream为输入文件流(从文件读入)
  ifstream inFile("/home/patten/workspace/others/data1.csv", ios::in);
  string lineStr;

  //部分编译器对“>>”编译会报错“error: ‘>>’ should be ‘> >’ within a nested template argument list”
  //所见建议对“<vector<string>>”添加一个空格“<vector<string> >”
  vector<vector<string> > strArray;

  // getline来自sstream
  while (getline(inFile, lineStr)) {
    //打印整行字符串
    // cout<<lineStr<<endl;
    //存成二维表结构
    stringstream ss(lineStr);  //来自sstream
    string str;
    vector<string> lineArray;

    //按照逗号分隔
    //一行数据以vector保存
    while (getline(ss, str, ',')) lineArray.push_back(str);

    //每一行vector数据都放到strArray中去
    strArray.push_back(lineArray);
  }
  //输出结果
  for (int i = 0; i < strArray.size(); i++) {
    for (int j = 0; j < strArray[i].size(); j++) cout << strArray[i][j] << "  ";
    cout << endl;
  }
  getchar();  //用户输入的字符被存放在键盘缓冲区中,直到用户按回车为止(防止程序一闪而过)

  return 0;
}

编译运行结果

结果如下:

patten@patten-hp:~/workspace/xjCollide$ g++ collide.cpp 
patten@patten-hp:~/workspace/xjCollide$ ./a.out 
name  age  hobby  
xiaoming  18  music  
Mike  21  football  
Tom  23  basketball  

patten@patten-hp:~/workspace/xjCollide$ 

生成如下文件(/home/patten/workspace/others/data1.csv):

name,age,hobby
xiaoming,18,music
Mike,21,football
Tom,23,basketball

致谢

踏莎行的博客C/C++读写csv文件