Click here to Skip to main content
15,919,931 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <iostream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int main() 
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);
    int operand1, operand2, result;
    stack<char>operation;
    
    int i=0;
    while (i < input.length()) 
    {
        if (isdigit(input[i])) 
        {
            operation.push(input[i]);
        } 
       
        else 
        {
          operand2 = operation.top();
          operation.pop();
          operand1 = operation.top();
          operation.pop();
          switch(operation.top())
          {
                  case '+': result=operand1 + operand2;
                  operation.push(result);
                  break;
                  case '-': result=operand1 - operand2;
                  operation.push(result);
                  
                  break;
                  case '*': result=operand1 * operand2;
                  operation.push(result);
                  
                  break;
                  case '/': result=operand1 / operand2;
                  operation.push(result);
                  
                  break;   
        }
          
        }
        i++;
    }
    
    while (!operation.empty()) 
    {
        cout << operation.top();
        operation.pop();
    }
      
  
    cout << "The result is: "<<result<<endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    return 0;
}


The code did not have any error but when i run it, this warning appear :

~~has encountered a problem and needs to close.
we are sorry for the inconvenience.

what is wrong with the code?
Posted

It doesn't work?

The first thing that springs to mind, is that you do no useful checking on what the user entered.

The second is that what happens if the first character entered is not a digit?

I strongly suggest that you learn to use the debugger.

Put a breakpoint on the line
while (i < input.length())
and single step it through, looking at the variables as you go. Before each step, you should have a good idea in you mind of what you expect to happen. Check it did. If not, why not? change your code, and try again. It is the only way you are going to learn.

I would suggest that you start by setting a known, static input string, rather than typing it each time - that way you can simplify the run and reduce the number of variables.
 
Share this answer
 
The easiest and most efficient way to find your problem is to use the debugger to see where your program crashes.

And you don't do any syntax checking in your program. You assume that the input string is properly formated. It would probably be good to do it. For example the only allowed characters in this code are "0123456789+-*/".
What will happen if you use spaces or float values (you don't handle the '.' character)?

And by the way, you can't handle numbers higher than 9 with this test:
if (isdigit(input[i]))
{
     operation.push(input[i]);
}
 
Share this answer
 
v2
Comments
nanaheartilly 12-Apr-11 3:50am    
but when i entered the value like "0123456789+-*/", the program also cannot run.
Olivier Levrey 12-Apr-11 3:59am    
You misunderstood me. I said that in your code: - the only allowed characters are: '0', and '1', and '2', and so on... - you can't pass numbers with two digits: 4 or 5 for example will be ok but 12 or 589 or 1420 will not. - if don't check the syntax of your input string
You didn't push your operator on the stack, yet you try to pop it from an empty stack.

[edit]Just in case you don't know what I'm talking about, it's the switch statement. Your
switch(operation.top())
refers to an empty stack, causing the error. Replace it with
switch (input[i])
and it might work.[/edit]

P.S.: (for the sake of completeness)
After a short exchange of a preliminary solution based on this answer (see Solution from OP), the additional fixes required were:

- Change stack<char>operation; to stack<int>operation;
- Change operation.push(input[i]); to operation.push(input[i]-'0');
 
Share this answer
 
v3
Comments
Olivier Levrey 12-Apr-11 5:36am    
Good catch. I hadn't seen that one.
The following code works a bit better, however you've to make it more robust (and hopefully elegant):

C++
#include <iostream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int main()
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);
    int operand1, operand2, result;
    stack<char>operation;

    int i=0;
    while (i < input.length())
    {
        // skip whitespaces
        if ( isspace(input[i]) )
        {
        }
        // accumulate a multi-digit number
        else if ( isdigit( input[i] ))
        {
          int num = 0;

          do
          {
            num = num*10 + (input[i]-'0');
            i++;
            if ( i >= input.length())
            {
              // handle error
            }
          } while (isdigit(input[i]));
          operation.push(num);
        }
        else
        {
          operand2 = operation.top();
          operation.pop();
          operand1 = operation.top();
          operation.pop();
          switch(input[i])
          {
                  case '+': result=operand1 + operand2;
                  operation.push(result);
                  break;
                  case '-': result=operand1 - operand2;
                  operation.push(result);

                  break;
                  case '*': result=operand1 * operand2;
                  operation.push(result);

                  break;
                  case '/': result=operand1 / operand2;
                  operation.push(result);

                  break;
          }

        }
        i++;
    }

    while (!operation.empty())
    {
        cout << operation.top();
        operation.pop();
    }


    cout << "The result is: "<<result<<endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    return 0;
}
 
Share this answer
 
#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;

int main()
{
    string input;
    cout << "Enter a postfix expression: " << endl;
    getline(cin, input);
    int operand1, operand2, result,number;
    stack<char>operation;
    stringstream temp;
    int i=0;
    while (i < input.length())
    {
        if (isdigit(input[i]))
        {
            operation.push(input[i]);
        }
        else
        {
          operand2 = operation.top();
          temp << operation.top();
          operation.pop();
          operand1 = operation.top();
          temp << operation.top();
          operation.pop();
          switch(operand1,operand2)
          {
                  case '+': result=operand1 + operand2;
                  break;
                  case '-': result=operand1 - operand2;
                  break;
                  case '*': result=operand1 * operand2;
                  break;
                  case '/': result=operand1 / operand2;
                  break;
        }
        operation.push(result);
        }
        i++;
    }
    cout << "The result is: "<<temp.str()<<endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    return 0;
}



i changed the code. it worked until pop only. :(
the operation didnt worked.
 
Share this answer
 
Comments
Stefan_Lang 12-Apr-11 12:19pm    
See my response above (Solution 2). I elaborated on my rather short answer in the meantime: you need to fix your switch statement.
nanaheartilly 12-Apr-11 13:12pm    
fixed
'switch(input[i])'

but when i enter 24+3*, it didnt give the right answer.
when i enter 52-, it give the right answer. only - works.
but when i enter 52-1-, wrong again. :(
Stefan_Lang 13-Apr-11 3:54am    
Two more errors:
1. you are reading char values, but then interpret them as int without concern for the ASCII code (or whatever code table you are using). In ASCII, the character '5' is encoded as 0x35, or 53 in decimal. So when you enter 5, the operand stored will be 53, not 5! An easy way to translate character input into the numeric values of the digits they are supposed to represent is

if (isdigit(input[i])) {
operation.push(input[i]-'0');
}


This assumes the digits 0 through 9 use consecutives codes in your code table: the integer value of the digit then equals the difference between the code of your digit and the code of 0 (which is the character '0').

2. You are using char and int values interchangably. When you push the intermediate result (an int value) onto the stack of char values, you are truncating that value to a range of at most [-128,127]. Since all your other variables are int already, I suggest you change your stack to std::stack<int>.

P.S.: Just as an example of what I think your code currently makes of the strings you gave as an example:
"24+3*" translates into ('2'+'4')*'3' = (50+52)*51 = 5202 = 0x1451 ==> 0x51(char) = 81
"52-" translates into '5'-'2' = 53-50 = 3
"52-1-" translates into ('5'-'2')-'1' = (53-50)-49 = -46 = 0xC2 (not sure how this prints)
nanaheartilly 13-Apr-11 5:02am    
all done!!!! thank you very much!!!!!! (^.^)v
You have done some minor mistakes...

First:
You should use
C#
if (isdigit(input[i]))
{
    operation.push(input[i] - '0';);
}

to push input in numeric onto stack !!!

Second:
Use
C#
switch(input[i])

as you have not pushed operator onto stack... :)

Third:
same problem in outputting result from stack...
C#
while (!operation.empty())
{
    cout<<static_cast<char>(operation.top() + '0';);
    operation.pop();
}
</char>

but there is one problem as it cannot handle -ve results.
You have to code with a better parsing approach.


Hope all this will help you!!!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900