someguyal
someguyal

Reputation: 1

Writing a postfix calculator with a stack and iterator

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

using namespace std;

int main()
{
    string blah("512+4*+3−");
    stack<int> astack;
    int a=0;
    int b=0;
    int result=0;
    int final=0;
    for (string::iterator count=blah.begin(); count != blah.end(); count=count+1)
    {
        if (isdigit(*count))
        {
            astack.push(*count);
            cout<<" "<<*count<<" ";
        }   
        else
        {
            a=astack.top();
            astack.pop();
            b=astack.top();
            astack.pop();
            if(*count=='+')
            {
                result = a+ b;
            }
            else if (*count=='-')
            {
                result=a-b;
            }
            else if(*count=='*')
            {
                result=a*b;
            }   
            astack.push(result);    
        }
    }       
    final=astack.top();
    cout<<final;
}

My problem is whenever I run it, the code seems to segment fault. When I tried running it with the operator commented it the stack seems to pop two values and I'm not really sure why

Upvotes: 0

Views: 268

Answers (2)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

If the code you posted is the actual code, then there is an issue with the string you posted.

string blah("512+4*+3−");

That last character after the 3 is not an ASCII minus sign. It is a Unicode character 0x2212. Change this to an ASCII minus and rerun the program.

What may have happened is that you started out with an ASCII minus, copied the text to another app, and the app tries to "fancy up" the minus by replacing it with more aesthetic looking character. Then you may have copied the text from this app back to your source code editor.

Upvotes: 1

Ryan Henning
Ryan Henning

Reputation: 126

As PaulMcKenzie pointed out, your minus sign in the blah string is some sort of weird unicode character that looks like a normal minus sign, but it isn't. Since it's some weird unicode character, it is actually being stored in more than one byte in the string's memory, meaning your iterator for-loop is iterating more times than you would expect!

Put a cout << blah.length() << endl; right after you declare blah, and you'll see that the length is more than the expected 9 characters.

Also, this program will not output the right answer even when the problem above is fixed. You need to convert your ascii number characters (which are in the integer range [48,57]) to the equivalent integer values before you do any calculations with them.

Upvotes: 1

Related Questions