View Code of Problem 16

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
string change(int a) {
	switch (a)
	{
	case 0:return "zero";break;
	case 1:return "one";break;
	case 2:return "two";break;
	case 3:return "three";break;
	case 4:return "four";break;
	case 5:return "five";break;
	case 6:return "six";break;
	case 7:return "seven";break;
	case 8:return "eight";break;
	case 9:return "nine";break;
	default:
		break;
	}
}
int change(string a) {
	if (a == "zero")return 0;
	if (a == "one")return 1;
	if (a == "two")return 2;
	if (a == "three")return 3;
	if (a == "four")return 4;
	if (a == "five")return 5;
	if (a == "six")return 6;
	if (a == "seven")return 7;
	if (a == "eight")return 8;
	if (a == "nine")return 9;
}

int main() {
	int t;
	cin >> t;
	while (t--) {
		int type;
		cin >> type;
		string a;
		getline(cin, a);//消除回车
		getline(cin, a);
		string front, behand;
		int fr = 0, be = 0, court = 0, bg = 0, flag = 0;
		for (int i = 0; i < a.size(); i++)//获取两个常数
		{
			if (a[i] == '+') {
				front = a.substr(0, i - 1);
				behand = a.substr(i + 2, a.size() - i - 4);
			}
		}
		//front——————————————————————————————————
		if (!isalpha(front[0])) {//如果不是英语
			string temp= front;
			front = "";
			for (int i = 0; i < temp.size(); i++)
			{
				front += change(temp[i]-'0');
				if (i != temp.size() - 1)front += " ";
			}
		}if (!isalpha(behand[0])) {//如果不是英语
			string temp = behand;
			behand = "";
			for (int i = 0; i < temp.size(); i++)
			{
				behand += change(temp[i] - '0');
				if (i != temp.size() - 1)behand += " ";
			}
		}
		for (int i = 0; i < front.size(); i++)//判断为几位数字
		{
			if (front[i] == ' ') {
				court++;
			}
		}
		for (int i = 0; i < front.size(); i++)
		{
			if (front[i] == ' ' && flag == 0) {//截取
				fr += change(front.substr(bg, i - bg)) * pow(10, court);
				court--;
				flag = 1;
			}
			if (flag == 1 && front[i] == ' ') {
				bg = i + 1;
				flag = 0;
			}
			if (i == front.size() - 1) {
				fr += change(front.substr(bg, front.size() - bg)) * pow(10, court);
				court--;
			}
		}
		//behand————————————————————————————————————
		court = 0, bg = 0, flag = 0;
		for (int i = 0; i < behand.size(); i++)//判断为几位数字
		{
			if (behand[i] == ' ') {
				court++;
			}
		}
		for (int i = 0; i < behand.size(); i++)
		{
			if (behand[i] == ' ' && flag == 0) {//截取
				be += change(behand.substr(bg, i - bg)) * pow(10, court);
				court--;
				flag = 1;
			}
			if (flag == 1 && behand[i] == ' ') {
				bg = i + 1;
				flag = 0;
			}
			if (i == behand.size() - 1) {
				be += change(behand.substr(bg, behand.size() - bg)) * pow(10, court);
				court--;
			}
		}
		int re = fr + be;
		if (type == 0) {
			cout << re;
			if (t != 0) cout << endl;
		}
		else {
			string reS = to_string(re);
			for (int i = 0; i < reS.size(); i++)
			{
				cout << change(reS[i] - '0');
				if (i != reS.size() - 1)cout << " ";
				else if (t != 0) cout << endl;
			}
		}
	}
}

Double click to view unformatted code.


Back to problem 16