POJ 1539 UVA 327 Evaluating Simple C Expressions
先处理双目运算符,然后去掉双目运算符,在处理单目运算符水过。。
#include <iostream>
using namespace std;
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char sb[115];
char sb1[115];
char sb2[115];
int num[26];
int num1[26];
int t;
int value;
int main()
{
while (gets(sb) != NULL)
{
value = 0;
memset(num, 0 ,sizeof(num));
memset(num, 0 ,sizeof(num1));
for (int i = 0; i < 26; i ++)
{
num[i] = i + 1;
num1[i] = i + 1;
}
memset(sb1, 0, sizeof(sb1));
memset(sb2, 0, sizeof(sb2));
t = 2;
sb1[0] = sb1[1] = ' ';
for (int i = 0; i < strlen(sb); i ++)
if (sb[i] != ' ')
sb1[t++] = sb[i];
sb1[t] = '\0';
for (int i = 0; i < strlen(sb1); i ++)
{
if (isalpha(sb1[i]))
{
if (sb1[i - 2] == '+' && sb1[i - 1] == '+')
{
num[sb1[i] - 'a'] ++;
num1[sb1[i] - 'a'] ++;
sb1[i - 2] = ' ';
sb1[i - 1] = ' ';
}
if (sb1[i - 2] == '-' && sb1[i - 1] == '-')
{
num[sb1[i] - 'a'] --;
num1[sb1[i] - 'a'] --;
sb1[i - 2] = ' ';
sb1[i - 1] = ' ';
}
if (sb1[i + 1] == '+' && sb1[i + 2] == '+')
{
num[sb1[i] - 'a'] ++;
sb1[i + 2] = ' ';
sb1[i + 1] = ' ';
}
if (sb1[i + 1] == '-' && sb1[i + 2] == '-')
{
num[sb1[i] - 'a'] --;
sb1[i + 2] = ' ';
sb1[i + 1] = ' ';
}
}
}
t = 1;
sb2[0] = ' ';
for (int i = 0; i < strlen(sb1); i ++)
{
if(sb1[i] != ' ')
sb2[t++] = sb1[i];
}
sb2[t] = '\0';
for (int i = 0; i < strlen(sb2); i ++)
{
if (isalpha(sb2[i]))
{
if (sb2[i - 1] == '-')
{
value -= num1[sb2[i] - 'a'];
}
else
{
value += num1[sb2[i] - 'a'];
}
}
}
printf("Expression: %s\n", sb);
printf(" value = %d\n", value);
sort(sb2,sb2+strlen(sb2));
for (int i = 0; i < strlen(sb2); i ++)
{
if(isalpha(sb2[i]))
{
printf(" %c = %d\n", sb2[i], num[sb2[i] - 'a']);
}
}
}
return 0;
}