Program For Evaluating Postfix Expression Using Stack Stone

Posted on -
Active1 year, 7 months ago

Postfix is an email service that can be downloaded free from open sources. Postfix offers some protection from spambots and malware, but is best used in conjunction with other antivirus software. C Program to Convert Infix expression to Postfix Expression using Stack. Used PUSH, POP and Priority functions. C Program to Convert Infix to Postfix Expression using Stack. More C Programs. Simulate Bankers Algorithm for Deadlock Avoidance Using C.

I've changed the code and managed to obtain the 'pop' value, but the operation didn't work.

Jens Erat
30.2k15 gold badges66 silver badges85 bronze badges
appleLadyappleLady

3 Answers

Peter Mortensen
14.4k19 gold badges88 silver badges117 bronze badges
TimTim
7,4343 gold badges33 silver badges50 bronze badges

Update response to code changes

I can confirm you changed the code, but not in a good way.

  1. The code mostly has all the flaws it already had, and a few more.
  2. What good is that you now combine the operands into a stringstream?
  3. You now switch on (operand1,operand2)...
    • both are uninitialized
    • (operand1,operand2) means basically (operand2) in this context (sequence operator)
    • your branch labels are ... operators (+-/*)
  4. you now print a final result which is the concatenation of all digits in the input (if you ever reach the end of the program without crashing)?

Among the things that were wrong before, and should still be fixed

  1. the mental model of a stack calculator.
    • numbers (integers) are the operands (so 9, 100, 39829 are valid operands)
    • +-/* are the operators (operatorsoperate on the operands)
    • the stack is an operand stack, not an operator stack (operators do not have to be remembered, because they are evaluated immediately)
    • numbers consist of 1 or more digits (0123456789) in a row; so you'd need to read several characters before you can 'push' a number on the operand stack
    • the operators +-/* take 2operands, so any operation on a stack of size<2 is an error (you need to check that or the program will crash while trying to access memory that doesn't exist or contains rubbish).

That should be enough to get you started.

Two things I do think are positive:

  1. You program compiles. +1 for you actually using a compiler there :)
  2. You took the repeated operation.push(result) out of the switch so it isn't duplicated anymore. +1 for coding style ...

I hope you can gather from this that the code isn't very good (to put it mildly), and I really think some basic exercises are in order: 1. write a simple for loop that prints numbers 1 to 10 to the console 1. write a simple while loop that prints words entered by the user 1. use a simple loop to print all numbers between 1 and 50 that are multiples of 7 1. use a switch statement to print 'yes' whenever the user enters one of the letters a, b, k, or z 2. make a simple loop that only prints the input character for every character that follows the identical (so 'abccdefgghijkllmabcdd' would become 'cgld') 1. use the same loop but this time print every word that immediately follows the identical word (so 'no, no, you should not pop, pop, but push, pop' becomes 'no pop')

That should give you a feel for how things really work, without the guesswork or the 'magic factor'.

Program For Evaluating Postfix Expression Using Stack Stone

Oh, and don't forget, I implemented the whole thing for you below. I don't suggest you blindly copy it (it will be rather obvious to your teacher :)) but it is there for you to take a peek if you want to know, what I mean with all my words above :)

  1. You are pushing loose digits, not parsed numbers

  2. In line 31 you pop a possibly empty stack (resulting in segfault unless you use the debug-mode STL flags on your compiler)

Just for fun:

Test output: (note that you can continue with the remaining, partially evaluted, stack after pressing carriage return)

sehesehe
287k35 gold badges363 silver badges488 bronze badges

There are many things wrong with the code, starting with parsing of the input expression. The actual crash is most probably due to the fact that if you input something like '12+' you will push '1' and '2' into the stack (note: characters 1 and 2, not values 1 and 2!!!) and then try to extract two operands and an operator that you never inserted into the stack.

On parsing the input, you are reading character by character, and only using the first digit, the parsing is not able to handle spaces or any other separator... Try to break the problem in two: parsing and processing. The problem of parsing can be tackled by not using the actual values read, but just printing them (or storing in some form and then printing the whole read expression), and can be a first step. Ensure that the parser is able to deal with common expressions like '1 2 +', '10 20 +', '1 2+', ' 1 2 + ' (note the different positions of spaces) in a robust way. And that it fails gracefully to parse expressions like ' +', '1 +', '1 2 ++'... You can never trust user input, they will make mistakes and that should not bring your program to its knees.

Once you are sure that you are able to parse the input, start on the actual algorithm. Make it robust against invalid user inputs that you might have not been able to tackle before, like '10 0 /' and do the actual processing.

Learn to use the debugger, it will help you understand when things go south what are the reasons. The debugger would take less than one second to point at the specific problem in your code above, it will not tell you why it died, but it will show you how it died and what the state of the program was there. If my hunch is correct, then it will point you at the operation.top() instruction as the culprit, and you will be able to see that you were trying to extract more elements than were inserted. Execute a part of your program step by step to understand what it is actually doing, and you will notice that when you read '12+' you are actually storing two seemingly unrelated integers into the stack (the ASCII values of '1' and '2'...

David Rodríguez - dribeasDavid Rodríguez - dribeas
178k16 gold badges242 silver badges444 bronze badges

Not the answer you're looking for? Browse other questions tagged c++stackevaluationpostfix-notation or ask your own question.

Active8 months ago

I was on here a while a go with a similar problem but I think with the wrong question. To give a bit of background, I a tasked with creating a C program to solve a postfix expression in the form

8 7 - 9 * =

What I think my problem is, is that my prof gave as some incorrect stack code. I say this because I am constantly getting the stack overflow (lol) error and my stack is nowhere near full. If it helps I'm using visual studio 2005. Here's my code:

Now I realize that my code is a little barbaric right now and for that I apologize. That being said, any help or input at all would be greatly appreciated and thank you all in advance.

Ok, so after taking everything into account, I think I'm getting close. Everything going into the stack properly and everything is being read properly. However, my new implementation includes making everything a character and then converting the integers when they need to be used. Here is my source code once again:

Please keep in mind that I have been playing around with it quite a bit, so there are random printfs and useless variables all for debugging purposes. Whenever I run it (with example input 3 5 + =) I get:

So again, please excuse my some what messy code as I am quite new to C but any help would be great!

Cœur
22.2k10 gold badges128 silver badges182 bronze badges
AndrewziacAndrewziac

3 Answers

This is an endless loop:

scanf returns the number of fields read successfully. In your case this can be 0 or 1. You are comparing it to '=' which is ASCII 61. So the '!=' is always true and you never come past this loop.

BTW, if you look at how push is implemented you see that the check for 'stack overflow' is done using the is_full() function. is_full() is comparing top against STACK_SIZE. You are comparing top20. You better should use is_full. This is more abstract and would work even if someone changed STACK_SIZE. You could even omit your checks for top20 and top0 because the only thing you do is call stack_underflow/stack_overflow, which is already done by the pop/push functions.

Werner HenzeWerner Henze
11.2k8 gold badges30 silver badges56 bronze badges

I don't see any problem with the stack. But there are at least two problems in your main.

push(&bit);

push accepts a Bit, not a Bit *. You should get a warning here, which you probably have ignored. Do not ignore the warnings.

while(scanf('%d',&current)!= '=')

This is definitely wrong. scanf retuns the number of successful input.

Program For Evaluating Postfix Expression Using Stack Stone For Fire Pit

operand1 operand2 operand3 operand4 operand5 operand6 operand7 operand8 operand9 operand0

Though this is not a bug, why should you write like this? You can easily replace with:

operand >= 0 && operand <= 9

And there might be many more problems.

taskinoortaskinoor
40.9k8 gold badges105 silver badges130 bronze badges

You have a problem with the following line:

The scanf function returns the number of items scanned, not the item. And scanning for %d will attempt to get an integer, not a character.

I think you should be looking more into something like:

which will push integers on to the stack until it can no longer scan one (i.e., you get an operation).

Stack

This is almost certainly your problem since that particular scanf will generally only return 0 or 1, meaning it will never be equal to = (which is hex 0x3d or decimal 61 if you're using ASCII). It could return EOF in some cases but that still won't give you a value of 61.

The fact that it will never return 61 means that it will simply keep looping, pushing the value of current on to your stack until it overflows, which is the behaviour you're seeing.

paxdiablopaxdiablo

Program To Evaluate Postfix Expression

667k185 gold badges1324 silver badges1724 bronze badges

Prefix Expression

Not the answer you're looking for? Browse other questions tagged cpostfix-notation or ask your own question.