1. 程式人生 > >STL 使用ofstream + ifstream 讀寫csv檔案

STL 使用ofstream + ifstream 讀寫csv檔案

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