C++將csv檔案資料讀入陣列中
阿新 • • 發佈:2019-02-04
將形如 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;
}