废话没有自己上代码:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
//删除字符串中空格,制表符tab等无效字符
string Trim(string& str)
{
//str.find_first_not_of(" \t\r\n"),在字符串str中从索引0开始,返回首次不匹配"\t\r\n"的位置
str.erase(0, str.find_first_not_of(" \t\r\n"));
str.erase(str.find_last_not_of(" \t\r\n") + 1);
return str;
}
int main()
{
std::cout << "Hello World!\n";
// 写文件
ofstream outFile;
outFile.open("data.csv", ios::out); // 打开模式可省略
outFile << "name" << ',' << "age" << ',' << "hobby" << ',' << "shengao" << endl;
outFile << "Mike" << ',' << 18 << ',' << "paiting" << ',' << "138" << endl;
outFile << "Tom" << ',' << 25 << ',' << "football" << ',' << "148" << endl;
outFile << "Jack" << ',' << 21 << ',' << "music" << ',' << "158" << endl;
outFile.close();
//读取csv文件到二维字符串数组
vector<vector<string>> biao; //声明一个字符串向量数组的向量
ifstream fin("data.csv"); //打开文件流操作
string line;
while (getline(fin, line)) //整行读取,换行符“\n”区分,遇到文件尾标志eof终止读取
{
cout << "原始字符串:" << line << endl; //整行输出
istringstream sin(line); //将整行字符串line读入到字符串流istringstream中
vector<string> fields; //声明一个字符串向量
string field;
while (getline(sin, field, ',')) //将字符串流sin中的字符读入到field字符串中,以逗号为分隔符
{
fields.push_back(field); //将刚刚读取的字符串添加到向量fields中
}
biao.push_back(fields); //将字符串数组添加到表数组中,变成二维数组
string name = Trim(fields[0]); //清除掉向量fields中第一个元素的无效字符,并赋值给变量name
string age = Trim(fields[1]); //清除掉向量fields中第二个元素的无效字符,并赋值给变量age
string birthday = Trim(fields[2]); //清除掉向量fields中第三个元素的无效字符,并赋值给变量birthday
int shengao = atoi(fields[3].c_str()); //string转换为int
cout << "处理之后的字符串:" << name << "\t" << age << "\t" << birthday << "\t" <<shengao << endl;
}
//cout << "biao中的字符串:" << biao[0][3] << "\t" << biao[1][3] << "\t" << biao[2][3] << "\t" << biao[3][3] << endl;
for (int i=0; i < 4; i++)
{
cout << "biao中的字符串:" << biao[i][0]<< "\t" << biao[i][1] << "\t" << biao[i][2] << "\t" << biao[i][3] << endl;
}
return EXIT_SUCCESS;
//return 0;
}