Output shows un common characters while changing from infix to postfix notation using C++

106 Views Asked by At
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.

2

There are 2 best solutions below

5
On BEST ANSWER

The problem is that you process p_newStr without initializint it, and only performing pointer arithmetic on it. I guess, that you wanted to see it as a string, adding chars to it.

So first initialisze it:

    char* p_newStr = newStr; // It was unitinitalised, pointing at random location

Then note that p_newStr = p_newStr + str[i] means adding the value of the char str[i], converted to int, to the pointer p_newStr. That's pointer arithmetic. Replace this statement with:

    *p_newStr++ = str[i];   // instead of p_newStr = ... 

and there is another one taking a char from the stack[]:

    *p_newStr++ = stack[top];   // instead of p_newStr = ... 

Finally, put an ending null terminator to the c string you've built, just before your printf():

    *p_newStr++ = 0;

Once these corrections made, the code produces exactly the expected results.

0
On
p_newStr = p_newStr + str[i];

Should be:

*p_newStr++ = str[i];

The way you currently have it, you are never actually modifying the new string. You make this mistake in two places.