Input:
3
(a+(b*c))
((a+b)*(z+x))
((a+t)*((b+(a+c))^(c+d)))
Output:
abc*+
ab+zx+*
at+bac++cd+^*
There are brackets in all the inputs, so precedence order of operators need not be checked. The following is my solution:
#include <stdio.h>
#include <string.h>
int main (void)
{
unsigned short t;
int len ,top = -1, i;
char str[400], newStr[400], stack[400];
char* p_newStr = newStr;
scanf("%hu", &t);
while (t--)
{
if (scanf("%s", str) <= 400)
{
len = strlen(str);
i = 0;
while(i < len)
{
if (str[i] >= 97 && str[i] <= 122)
{
p_newStr = p_newStr + str[i];
}
else if (str[i] == '(' || str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' || str[i] == '^')
{
top++;
stack[top] = str[i];
}
else if (str[i] == ')')
{
while(stack[top] != '(')
{
p_newStr = p_newStr + stack[top];
top--;
}
top--; //the '(' is discarded from the stack.
}
i++;
}
printf ("%s\n", newStr);
}
}
return 0;
}
I do not have much experience with handling strings in C or C++ using character arrays or library classes. When I run it, I get un recognizable symbols instead of the correct postfix notation.