STL 使用ofstream + ifstream 读写csv文件

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

#include "stdafx.h"
#include 
#include 
#include 
#include 
#include 

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 subArray;

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

		//输出解析后的每行数据
		for (size_t i=0; i

 

你可能感兴趣的:(STL,/,boost)