UVA 327 Evaluating Simple C Expressions

#include <cstdio>
#include <cctype>

int main() {
	char expre[256];
	while (gets(expre)) {
		printf("Expression: %s\n", expre);
		int  vari[26][2] = {0}, count = 0, sum = 0;
		for (int i = 0; i < 26; i++) //初始化字符的值
			vari[i][0] = i + 1;
		for (int i = 0; expre[i]; i++) {
			if (isalpha(expre[i])) //查找出出现的字符
				vari[expre[i] - 'a'][1]++;
			if (expre[i] != ' ') //把表达式中的空格去掉
				expre[count++] = expre[i];
		}

		for (int i = 0; i < count; i++) {
			int num = 0, flag = 0;
			if (isalpha(expre[i]) && expre[i + 1] == '+' && expre[i + 2] == '+') //如果有后缀,num值等于字符为变化前的值
				num = vari[expre[i] - 'a'][0]++, flag = 1; 
			else if (isalpha(expre[i]) && expre[i + 1] == '-' && expre[i + 2] == '-')
				num = vari[expre[i] - 'a'][0]--, flag = 1; 
			else if ( expre[i] == '+' && expre[i + 1] == '+' && isalpha(expre[i + 2])) //如果有前缀,num值等于字符变化后的值
				num = ++vari[expre[i + 2] - 'a'][0], flag = 1; 
			else if ( expre[i] == '-' && expre[i + 1] == '-' && isalpha(expre[i + 2]))
				num = --vari[expre[i + 2] - 'a'][0], flag = 1; 
			if (flag) { //如果有前缀或后缀,把前缀或后缀并且和字符一起变成空格
				expre[i] = ' ';
				expre[++i] = ' ';
				expre[++i] = ' ';
			}
			if (isalpha(expre[i])) //获取没有前缀或后缀的字符的值
				num = vari[expre[i] - 'a'][0]; 
			for (int j = i-1 ; j >= 0; j--) //判断该字符前面有没负号;
				if (expre[j] == '-') { //如果有负号,把num值变为负, 并且把 '-' 变成空格;
					num *= -1; 
					expre[j] = ' ';
				}
			sum += num; //加上num值
		}
		printf("    value = %d\n", sum);
		for (int i = 0; i < 26; i++)
			if (vari[i][1] != 0)
				printf("    %c = %d\n",'a' + i, vari[i][0]);
	}

	return 0;
}


你可能感兴趣的:(UVA 327 Evaluating Simple C Expressions)