简体   繁体   中英

my c++ postfix converter using stack library

I'm second year in CS I'm trying to create infix to postfix converter with this steps:

1.if the char is digit print
2- if it is '(' then add it to the stack

3-if it is ')' then pop to the output until it reaches '('

4- if it is operator the pop from the stack until it can be pushed into the stack depending on the priority of operators

5- show the final postfix equation

the problem is I need a loop to scan all the equation characters but I didn't know how to do it below is my C++ code

#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;


void scan(char);
int priority(char);
void st(char);
void move(char);
char expr;
int main() {

    cout << "enter an formula: ";
    cin >> expr;
    scan(expr);


    return 0;
}

void scan(char exp) {

    if (isdigit(exp)) {
        expr = putchar(exp);
        move(exp);

    }
    else {
        st(exp);
        move(exp);

    }

}

void move(char exp) {

    if (expr == exp)
        expr = getchar();

}


int priority(char exp) {

    if (exp == '(')
        return 1;

    else if (exp == ')')
        return 2;

    else if (exp == '%' || exp == '/' || exp == '*')
        return 3;

    else if (exp == '+' || exp == '-')
        return 4;


    return 0;
}

void st(char op) {
    std::stack<char> stack1;

    if (priority(op) == 1) {
        stack1.push(op);
    }

    else if (priority(op) == 2) {
        while (stack1.top() != '(') {
            putchar(stack1.top());
        }
        stack1.top();

    }

    else if (priority(op) == 3) {
        if (stack1.empty()) { stack1.push(op); }

        if (stack1.top() == '%' || stack1.top() == '/' || stack1.top() == '*')
        {
            putchar(stack1.top());
        }

        if (stack1.top() == '+' || stack1.top() == '-') { stack1.push(op); }
    }

    else if (priority(op) == 4) {
        if (stack1.empty()) { stack1.push(op); }

        if (stack1.top() == '%' || stack1.top() == '/' || stack1.top() == '*')
        {
            putchar(stack1.top());
        }

        if (stack1.top() == '+' || stack1.top() == '-') { putchar(stack1.top()); }

    }
}

So I think the mistake is here

char expr;

In C++ char is a type for a single character. It you want a string of characters use the type std::string (and also #include <string> )

string expr;

Then loop through the equation like this

for (char ch : expr)
    scan(ch);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM