I face the problem when i key in 5 5+ the result is 10.
But i key in 5 6+ he give the result 12.
Some equation can give me true result some give me false result.
Anyone can help me toubleshoot?
The following are my program:

[LIST=1]
[*]#include <iostream>
[*]#include <cctype>
[*]#include <string>
[*]#include "Stack.h"

[*]using namespace std;

[*]main()
[*]{
[*]	char ch;
[*]	string ch2;
[*]	nodeIntType operand1, operand2, result;

[*]	StackInt S;

[*]	InitializeStack(&S);

[*]	cout<<"Enter Postfix Expression :";
[*]	cin.get(ch);

[*]	while(ch !='\n'){

[*]		if (isdigit(ch))
[*]		{
[*]			ch2=ch2+ch;
[*]	
[*]		}
[*]		else if(ch==' ')
[*]		{
[*]			Push((nodeIntType)(atoi(ch2.c_str())),&S);
[*]			ch2="";
[*]		}

[*]		else if(ch =='+' || ch=='-' || ch=='*' || ch=='/'){
[*]			Pop (&S, &operand2);
[*]			Pop (&S, &operand1);

[*]			switch(ch){
[*]			case '+':result = operand1 + operand2;
[*]				break;
[*]			case '-':result = operand1 - operand2;
[*]				break;
[*]			case '*':result = operand1 * operand2;
[*]				break;
[*]			case '/':result = operand1 / operand2;
[*]				break;
[*]			}
[*]			Push(result, &S);
[*]		}
[*]		cin.get(ch);
[*]	}
[*]	Pop(&S , &result);

[*]	cout<<"Answer :"<<result<<endl;

[*]	return 0;
[*]}
[/LIST]

Does your stack fail if you try to pop more times than you push?
Do you check for that in your code (no)?

5 5+ would seem to fail to push two values, you detect a space, and there isn't one
5 5 + might fare better.

Consider initialising your operand variables to something obvious.

The validation i haven't done it.I try to do the main part of calculation 1st .But the problem is how to overcome this kind of problem.The program can work well but cannot calculate what i want.Someone please help me.

How are we supposed to help you when you haven't posted the whole code.

And saying that you haven't done the validation isn't an excuse. DO IT NOW and find out whether the code is going wrong because of it.

Also, get used to using a debugger. For example, prove to yourself that you're getting TWO pushes, followed by TWO pops. If you don't see that, then you've got a problem.

If you don't have a debugger, then put lots of cout statements in there to see what's going on.


> The program can work well but cannot calculate what i want.
What kind of asinine statement is that? It works, but doesn't do what I want?
To me, that means broken.
How do you know (since you have uninitialised data), that the apparent success is down to just dumb luck and absolutely nothing to do with your code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.