いつもの作業の備忘録

作業を忘れがちな自分のためのブログ

【C++】CSV形式を要素ごとに分割

CSVの行(文字列)を要素ごとに分割してvectorで受け取る。

vector<string> split(string str, char c){
	vector<string> v;
	string buf = "";
	stringstream ss;

	ss << str;
	while (getline(ss, buf, c)){
		v.push_back(buf);
	}

	return v;
}


サンプルコード

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

vector<string> split(string str, char c){
	vector<string> v;
	string buf = "";
	stringstream ss;

	ss << str;
	while (getline(ss, buf, c)){
		v.push_back(buf);
	}

	return v;
}

int main(int argc, char **argv){
	vector<string> vec;
	string line = "a\tb\tc\t1\t2\t3";	//分割すべき文字列

	vec = split(line, '\t');

	return 0;
}

変数 vec に"a"、"b"、"c"、"1"、"2"、"3"が string 型で入る。必要に合わせてstoi()とかで型変換するとよい。