C++将csv文件数据读入数组中

来源:互联网 发布:python google语音api 编辑:程序博客网 时间:2024/05/18 08:33

将形如 1,2,3
4,5,6
7,8,9
的csv文件数据放入二维数组中。

#include <iostream>  #include <string>  #include <vector>  #include <fstream>  #include <sstream>  using namespace std;  int main()  {      // 写文件      //ofstream outFile;      //outFile.open("data.csv", ios::out); // 打开模式可省略      //outFile << "name" << ',' << "age" << ',' << "hobby" << endl;      //outFile << "Mike" << ',' << 18 << ',' << "paiting" << endl;      //outFile << "Tom" << ',' << 25 << ',' << "football" << endl;      //outFile << "Jack" << ',' << 21 << ',' << "music" << endl;      //outFile.close();      // 读文件      ifstream inFile("E://1.txt", ios::in);      string lineStr;      vector<vector<string>> strArray;      int array[3][3];    int i,j;    i=0;    char* end;    if(inFile.fail())        cout<<"读取文件失败"<<endl;    while (getline(inFile, lineStr))      {          j=0;        // 打印整行字符串          cout << lineStr << endl;          // 存成二维表结构          stringstream ss(lineStr);          string str;          vector<string> lineArray;          // 按照逗号分隔          while (getline(ss, str, ','))          {            array[i][j]=static_cast<int>(strtol(str.c_str(),&end,10));              //string -> int            j++;        }        i++;        //     strArray.push_back(lineArray);      }        for(int i=0;i<3;i++)      {          for(int j=0;j<3;j++)              cout<<array[i][j];          cout<<endl;      }    getchar();     return 0;  }
原创粉丝点击