#include<bits/stdc++.h>
using namespace std;
void read_csv(string filename)
{
ifstream inFile(filename);
string lineStr;
vector<vector<string> > strArray;
cout<<"the whole line is: "<<endl;
while(getline(inFile,lineStr))
{
cout<<lineStr<<endl;
stringstream ss(lineStr);
string str;
vector<string> lineArray;
while(getline(ss,str,','))
{
lineArray.push_back(str);
}
strArray.push_back(lineArray);
}
cout<<"--------------------------------------------"<<endl;
cout<<"print what we have saved in the vector: "<<endl;
for(auto s : strArray)
{
for(auto x : s)
{
cout<<x<< " ";
}
cout<<endl;
}
}
void read_csv(string filename,int row,int col)
{
int i = 1;
ifstream inFile(filename);
string lineStr;
vector<vector<string> > strArray;
while(getline(inFile,lineStr)&&i<=row)
{
cout<<lineStr<<endl;
stringstream ss(lineStr);
string str;
vector<string> lineArray;
int j = 1;
while(getline(ss,str,',')&&j<=col)
{
lineArray.push_back(str);
j++;
}
i++;
strArray.push_back(lineArray);
}
cout<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<endl;
for(auto s : strArray)
{
for(auto x : s)
{
cout<<x<< " ";
}
cout<<endl;
}
}
int main()
{
string filename = "D:/test.csv";
read_csv(filename);
int i = 2,j=2;
read_csv(filename,i,j);
return 0;
}
原文件样式;
输出结果: 整个文件打印如下: 打印文件前两行前两列:
|