Fu-koの足跡

コンピュータが苦手です。得体のしれない感じに抵抗があります。考えるのは好きです。すっきりしたロジックに感動します。ちゃんと理解すれば好きになれるはずと信じて、その過程を残そうと思います。

トークン分割

std::stringにsplit関数がないので、std::getlineを使って分割する。

<ソース>

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

int main()
{
	std::vector<std::string> vec;
	std::string str;

	// 読み込み
	std::getline(std::cin, str);

	// ' ' で分割
	std::stringstream ss(str);
	while (std::getline(ss, str, ' ')) // 第3引数で区切り文字を指定
	{
		vec.push_back(str);
	}

	// 分割したトークンを出力
	for (std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it)
	{
		std::cout << *it << std::endl;
	}

	return 0;
}

<実行結果>

a bb c dd ee f    ->コンソールからの入力
a
bb
c
dd
ee
f