Question

So, I have the following (kludgy!) code for an infix to postfix expression converter and calculator (as I mentioned on my previous post: Simple numerical expression solver, thanks to everyone!):

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

using namespace std;

int main()
{
    stack<char> operators;  
    stack<char> output;
    stack<char> temp;       
    stack<char> answer; 

    string command;

    cout << "=>";
    cin >> command;

    // "Shunting Yard" algorithm
    // source: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
    for(int i=0; i<command.size(); i++)
    {
        switch(command[i])
        {
        case '*': case '+': case '-': case '/': case'(': 
            operators.push(command[i]);
            break;

        case ')':
            while(operators.top() != '(')
            {
                output.push(operators.top());
                operators.pop();
            }
            operators.pop();
            break;

        default:
            output.push(command[i]);
            break;
        }
    }

    while(!operators.empty())
    {
        output.push(operators.top());
        operators.pop();
    }

    while(!output.empty())
    {
        temp.push(output.top());
        output.pop();
    }

    while(!temp.empty())
    {
        if(temp.top() == '+')
        {
            int a = atoi(&answer.top());
            cout << "A=" << a << endl;
            answer.pop();
            int b = atoi(&answer.top());
            cout << "B=" << b << endl;
            answer.pop();
            answer.push(b+a);
        } else {
            answer.push(temp.top());
        }
        temp.pop();
    }

    cout << answer.top() << endl;

    system("pause");
    return 0;
}    

Anyway, the problem is: if I enter, for instance, 3+4, the result is "&", when the correct result would be "7". So, what's wrong with my code?

Était-ce utile?

La solution

There are two problems here.

First:

int a = atoi(&answer.top());

atoi takes a pointer to a null-terminated string of characters. But &answer.top() is just a pointer to a single character. So atoi is going to start reading from that character, then continue marching through memory until it finds a '\0' character (or a non-digit). Depending on how the stack is implemented on your platform, that may mean it reads the '4', then the '3', then a '\0', so it ends up with "43". Or it may read the '4', then some uninitialized memory that happens to start with "8675309j", so it ends up with "48675309".

In case you're wondering why the compiler doesn't warn you about this error, the problem is that C-style strings and pointers to single characters are syntactically the exact same type (char*), so a compiler can't tell you're mixing them up unless it understands the semantics of atoi. This is one of the many reasons that it's better to use the C++ string class and functions, instead of the C char* based functions.

Second:

answer.push(b+a);

b+a is an int, but you're pushing it into a stack of chars. So, even if it had the right value, you'd be pushing the character '\007', not the character '7'. You need to re-stringize it. But in this case, you've apparently got something like, say, 305419814, which is truncated to the low 8 bits (38) when cast to char, and 38 is '&'.

Autres conseils

Replacing this section of code:

if(temp.top() == '+')
    {
        int a = atoi(&answer.top());
        cout << "A=" << a << endl;
        answer.pop();
        int b = atoi(&answer.top());
        cout << "B=" << b << endl;
        answer.pop();
        answer.push(b+a);
    } 

with:

 if(temp.top() == '+')
    {
        int a = answer.top() - '0';
        cout << "A=" << a << endl;
        answer.pop();
        int b = answer.top() - '0';
        cout << "B=" << b << endl;
        answer.pop();
        answer.push(b+a);
    } 

will solve your problem.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top