UVA_327_Evaluating Simple C Expressions

#include<iostream>    
#include<sstream>    
#include<string>    
#include<vector>    
#include<list>    
#include<set>    
#include<map>    
#include<stack>    
#include<queue>    
#include<algorithm>  
#include<bitset>
#pragma warning(disable:4996)    
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
using std::priority_queue;
using std::bitset;
void evaluate(const string &str)
{
	map<char, int>char_val;
	char Operator = '+';
	int sum = 0;
	for (size_t i = 0; i < str.size();)
	{
		if (str.size() - i >= 3)
		{
			if (str[i] == '+'&&str[i + 1] == '+'&&isalpha(str[i + 2]))
			{
				if (Operator == '+')
				{
					sum += str[i+2] - 'a' + 2;
				}
				else
				{
					sum -= str[i+2] - 'a' + 2;
				}
				char_val.insert({ str[i+2],str[i+2]-'a' + 2 });
			}
			else if (str[i] == '-'&&str[i + 1] == '-'&&isalpha(str[i + 2]))
			{
				if (Operator == '+')
				{
					sum += str[i+2] - 'a';
				}
				else
				{
					sum -= str[i+2] - 'a';
				}
				char_val.insert({ str[i+2],str[i+2] - 'a' });
			}
			else if (isalpha(str[i]) && str[i + 1] == '+'&&str[i + 2] == '+')
			{
				if (Operator == '+')
				{
					sum += str[i] - 'a' + 1;
				}
				else
				{
					sum -= str[i] - 'a' + 1;
				}
				char_val.insert({ str[i],str[i] - 'a' + 2 });
			}
			else if (isalpha(str[i]) && str[i + 1] == '-'&&str[i + 2] == '-')
			{
				if (Operator == '+')
				{
					sum += str[i] - 'a' + 1;
				}
				else
				{
					sum -= str[i] - 'a' + 1;
				}
				char_val.insert({ str[i],str[i] - 'a' });
			}
			else
			{
				goto sign;
			}
			i += 3;
		}
		else
		{
		sign:
			if (isalpha(str[i]))
			{
				if (Operator == '+')
				{
					sum += str[i] - 'a' + 1;
				}
				else
				{
					sum -= str[i] - 'a' + 1;
				}
				char_val.insert({str[i],str[i]-'a'+1});
			}
			else
			{
				Operator = str[i];
			}
			i++;
		}
	}
	cout << "    value = " << sum << endl;
	for (auto iter = char_val.begin(); iter != char_val.end(); iter++)
	{
		cout << "    " << iter->first << " = " << iter->second << endl;
	}
}
string clear_space(const string &str)
{
	string ret;
	for (size_t i = 0; i < str.size(); i++)
	{
		if (!isspace(str[i]))
		{
			ret.push_back(str[i]);
		}
	}
	return ret;
}
int main()
{
	//freopen("input.txt", "r", stdin);    
	//freopen("output.txt", "w", stdout);
	string expression;
	while (getline(cin, expression))
	{
		cout << "Expression: " << expression << endl;
		expression = clear_space(expression);
		evaluate(expression);
	}
	return 0;
}

你可能感兴趣的:(uva)