STL 使用ofstream + ifstream 读写csv文件

版权声明:本文为博主原创文章,未经博主同意不可随意转载。 https://blog.csdn.net/hellokandy/article/details/81533909

csv文件,每行的数据是用逗号分隔的,读写csv文件的示例代码如下:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>

using std::ifstream;
using std::ofstream;
using std::stringstream;
using std::vector;
using std::string;
using std::ios;
using std::cout;
using std::endl;

int _tmain(int argc, _TCHAR* argv[])
{
	//写文件
	ofstream ofs;
	ofs.open("fruit.csv", ios::out); // 打开模式可省略
	ofs << "Apple" << ',' << 5.5 << ',' << "2.2kg" << endl;
	ofs << "Banana" << ',' << 4.5 << ',' << "1.5kg" << endl;
	ofs << "Grape" << ',' << 6.8 << ',' << "2.6kg" << endl;
	ofs.close();

	//读文件
	ifstream ifs("fruit.csv", ios::in);
	string _line;
	while (getline(ifs, _line))
	{
		//打印整行字符串
		cout << "each line : " << _line << endl;

		//解析每行的数据
		stringstream ss(_line);
		string _sub;
		vector<string> subArray;

		//按照逗号分隔
		while (getline(ss, _sub, ','))
			subArray.push_back(_sub);

		//输出解析后的每行数据
		for (size_t i=0; i<subArray.size(); ++i)
		{
			cout << subArray[i] << "\t";
		}
		cout << endl;
	}

	getchar();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hellokandy/article/details/81533909