what could the problem be?
Ok when I run my program I test 23+. It suppose to be converted to 2+3 and the answer should be 5. But when I run it it gives me the answer 2. Im not sure what the problem is. Ive use the debugger but Im not figuring out why I get 2.
Code:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
using namespace std;
const int DefaultListSize =50;
typedef float Elem;
class Link {
public:
Elem element; /*Value for this node*/
Link* next; /*Pointer to the next node in list*/
Link(const Elem& elemval, Link* nextval =NULL)
{ element = elemval; next = nextval; }
Link(Link* nextval =NULL) { next = nextval; }
};
class Lstack {
private:
Link*top; /*Pointer to first element*/
int size; /*Count number of elements*/
public:
Lstack(int sz =DefaultListSize) {top = NULL; size = 0;}
~Lstack() {clear();} /*Destructor*/
void clear() {
while (top != NULL) { /*Delete link nodes*/
Link*temp = top;
top = top->next;
delete temp;
}
size = 0;
}
bool push(const Elem& item) {
top = new Link(item,top);
size++;
return true;
}
bool pop(Elem& item) {
if(size == 0) return false;
item = top->element;
Link*ltemp = top->next;
delete top;
top = ltemp;
size--;
return true;
}
bool topValue(Elem& it) const {
if (size ==0) return false;
it = top->element;
return true;
}
int length() const {return size;}
bool isEmpty() const {
if (top == NULL) return true;
else return false;
}
};
bool Operand(float ch){
if(('0' <= ch) && (ch <= '9'))
return true;
else return false;
}
bool Operator(char ch){
if((ch == '+') || (ch =='-')|| (ch == '*') || (ch == '/') || (ch == '^'))
return true;
else return false;
}
float Eval(float oprndL, char oper, float oprndR);
int main(){
Lstack S;
string s;
float a = 0;
char b = 0;
float c = 0;
float answer;
unsigned int i;
cout << "Enter Postfix string:\n";
getline(cin, s);
for(i=0; i < s.length(); i++ ){
if(s.at(i) != '\0'){
if(Operand(s.at(i))){
S.push(Operand(s.at(i)));
}
else if(Operator(s.at(i))){
b = s.at(i);
}
}
}
if(!S.isEmpty()){
S.pop(c);
S.pop(a);
Eval(a, b, c);
S.push(Eval(a, b, c));
S.pop(answer);
cout << answer << endl;
}
return 0;
}
float Eval(float oprndL, char oper, float oprndR){
if(oper == '+') return oprndL + oprndR;
else if(oper == '-') return oprndL - oprndR;
else if(oper == '*') return oprndL * oprndR;
else if(oper == '/') return oprndL / oprndR;
else if(oper == '^') return pow(oprndL,oprndR);
else return 0.0;
}