Using Stacks In C++ for infix and postfix expressions

北城以北 提交于 2019-12-24 09:38:59

问题


I'm writing a program that takes user input and uses stacks to convert an infix expression into a postfix expression based on precedence, with operands always going before operators. For example, if a user inputs:

(a+b*c)

then the program should display:

abc*+

so far, I have this:

#include <iostream>
#include <stack>
#include <string>


using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != '\n')
        {
            if (isalnum(input))
                cout << input << "\n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty()) 
                    s.pop();
            else
                cout << "ERROR: No Matching ( \n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty()) 
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}

Which compiles and runs but is not functioning as it should. When an expression like "ab" is input, the program will display "ab" as it should but if I input "a+b+c", then only "a" will be displayed. This means the program is not placing the operators into the stack to be displayed later on. What I need help with is modifying the program so that when an operator is input, it should be added onto the stack and then displayed based on it's precedence (*>/>+>-) after the operands, when the input is done.

I'm quite new to C++ and programming in general, so any suggestions would be great.


回答1:


else if (input == '*'||'/'||'+'||'-' && s.top() >= input)

This does not do what you think it does. You need to do

else if (input == '*'|| input == '/'|| input == '+'|| input == '-' && s.top() >= input)

And this looks like an error too

bool prec (char a, char b, char c, char d);

That's the syntax for a function prototype. Are you sure this compiles?




回答2:


The problem is here:

bool prec (char a, char b, char c, char d);
return ('*' > '/' > '+' > '-');

I'm guessing this is intended to define a precedence function, but that's not what it's doing. The first line declares that such a function exists (and its arguments have nothing to do with the variables declared in the previous lines), and the second causes the whole program to terminate. If you want a function like this, you must define it outside main.

A slightly less dramatic bug is here:

if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input)

First, this part

input == '*'||'/'||'+'||'-'

is interpreted as

(input == '*') || ('/') || ('+') || ('-')

The last three terms are true, the first is irrelevant. And I'm not even sure what s.top() does if s is empty.

This should be enough to go on. I suggest you start by building and testing routines that can, e.g., identify the operators and evaluate their precedence, before you try putting everything together in one program.




回答3:


Falmarri is right just wanted to post that my self , and it compiles I tried it , but there is another thing : you said else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here? Are you sure that even reached that point because when I runn it , it just stops on the :

while (cin.get(input) && input != '\n')

until I hit enter and even more you can enter more then one char from consol while in cin.get(input) but the input will contain only the first char you entered . To solve this I just put an #include <conio.h>at the beginning an used

while ((input = getch()) && input != (char)13) in staid of you're code  

short explanation

getch()

returns after you press only one character and

input != (char)13 is required in staid of input != '\n' because getch() return (char)13 for ENTER see ASCII table for more info.



来源:https://stackoverflow.com/questions/4772802/using-stacks-in-c-for-infix-and-postfix-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!