C++读取CSV文件中的数据

CSV文件是一种文本文件,表示的是Excel表格数据,可以由办公软件Excel轻松生成。为了在程序中使用Excel数据,就需要以文本的形式操作Excel数据,具体就是操作CSV表格数据。如下所示,

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
 
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()
{
	ifstream fin("test1.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中
		}
		string name = Trim(fields[0]); //清除掉向量fields中第一个元素的无效字符,并赋值给变量name
		string age = Trim(fields[1]); //清除掉向量fields中第二个元素的无效字符,并赋值给变量age
		string birthday = Trim(fields[2]); //清除掉向量fields中第三个元素的无效字符,并赋值给变量birthday
		cout <<"处理之后的字符串:"<< name << "\t" << age << "\t" << birthday << endl; 
	}
	return EXIT_SUCCESS;
}
假设Excel数据如下图:

对应的CSV文件为,为了体现程序的一般性,此处将csv文件故意打乱添加一些无效字符,如下所示,

程序运行的结果如下图所示,



猜你喜欢

转载自blog.csdn.net/u013232740/article/details/50828062