#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
//打开要输入的文件
ofstream oFile;
oFile.open("1.csv", ios::out | ios::trunc); // 这样就很容易的输出一个需要的excel 文件
oFile << "姓名" << "," << "年龄" << "," << "班级" << "," << "班主任" << endl;
oFile << "张三" << "," << "22" << "," << "1" << "," << "JIM" << endl;
oFile << "李四" << "," << "23" << "," << "3" << "," << "TOM" << endl;
oFile.close();
//打开要输出的文件
ifstream iFile("1.csv");
string s1,s2,s3,s4;
while(getline(iFile,s1))
{
cout<<s1<<endl;
cout<<endl;
}
iFile.close();
//逐个提取以逗号分隔的词
ifstream inf;
inf.open("1.csv", ifstream::in);
const int cnt = 3; //一行有3个逗号
int j = 0;
size_t comma = 0;
size_t comma2 = 0;
while ( getline(inf,s2) )
{
comma = s2.find(',',0);
cout<<s2.substr(0,comma).c_str()<<'\t';
while (comma < s2.size() && j != cnt-1)
{
comma2 = s2.find(',',comma + 1);
cout<<s2.substr(comma + 1,comma2-comma-1).c_str()<<'\t';
++j;
comma = comma2;
}
cout<<endl;
j = 0;
}
inf.close();
return 0;
}
输出结果:
写的时候个字段要用逗号分隔,用空格不行;读的时候一次要读一行