九度問題1010:A+B

1089 ワード

文字列を処理すればいいです.コード:
#include <iostream>
#include <string>
#include <map>

using namespace std;

map<string, int> dict;
string str;
int a, b;

void init()
{
	dict["zero"] = 0;
	dict["one"] = 1;
	dict["two"] = 2;
	dict["three"] = 3;
	dict["four"] = 4;
	dict["five"] = 5;
	dict["six"] = 6;
	dict["seven"] = 7;
	dict["eight"] = 8;
	dict["nine"] = 9;
}

int string_to_int(const string& str)
{
	int ret = 0;
	for (size_t i=0, next=str.find(' '); 
		next!=string::npos; 
		i=next+1, next=str.find(' ',i))
	{
		ret = 10 * ret + dict[str.substr(i, next-i)];
	}
	return ret;
}	

int main()
{
	init();
	while (getline(cin, str))
	{
		int plus_index = str.find('+');
		int equal_index = str.find('=');
		a = string_to_int(str.substr(0, plus_index));
		b = string_to_int(str.substr(plus_index+2, equal_index-plus_index-2));
		if (a + b != 0)
		{
			cout << a + b << endl;
		} else 
		{
			break;
		}
	}

	return 0;
}