Hi! I am a student, in my first C++ class. I am trying to program a scanner that would take a string of non-numeric numbers postfix, convert to numeric numbers and give a value. I've exhausted all my resources and just can't figure out where my program is going wrong. Any suggestions would be greatly appreciated! This is my first time posting here, so I hope that I did this right. Thank you
No matter what string I enter (like "100 25 +"), I only get a value of 0. I think my problem is in my "int convert (char*)" function but I'm not sure.
Code:#include <iostream.h> #include <math.h> #define E 0 #define L 1 #define G 2 #define C -1 int strcomp (char*, char*); int eval (char*); int scanner (char*, int, char*); int convert (char*); class stack { public: int *arr; int ptr; int n; stack (int n); ~stack (); int push (int value); int pop (); int empty (); int full (); }; stack::stack (int value) { n = value; arr = new int [n]; ptr = 0; } stack::~stack () { delete []arr; } int stack::push (int value) { if (ptr < n) { arr [ptr] = value; ptr++; return E; } else return L; } int stack::pop () { ptr--; return arr [ptr]; } int stack::empty () { if (ptr == 0) return E; else return L; } int stack::full () { if (ptr == n) return E; else return L; } int main () { int n; char arr [100]; cin.getline (arr, 100); while ( strcomp(arr, "quit") != E) { n = eval (arr); cout << "The value of " << arr << " = " << n << endl; cin.getline (arr, 100); } } int strcomp (char*str1, char*str2) { int k = 0; while (str1 [k] == str2 [k]) { if (str1 [k] == '\0') return E; else k++; } if (str1 [k] < str2 [k]) return L; else return G; } int eval (char*str) { int pos = 0, value; char token [100]; stack stk1 (100); while (pos != C) { pos = scanner (str, pos, token); char fchar = token[0]; if (fchar == '+' || fchar == '-' || fchar == '*' || fchar == '/') { int opr1 = stk1.pop (); int opr2 = stk1.pop (); if (fchar == '+') value = opr1 + opr2; if (fchar == '-') value = opr1 + opr2; if (fchar == '*') value = opr1 + opr2; if (fchar == '/') value = opr1 + opr2; int rel = stk1.push (value); } else { int num = convert (token); int ret = stk1.push (num); } } return stk1.arr [0]; } int scanner (char*str, int str, char*token); { int i = st; while (str [i] != ' ') { if (str [i] == '\0') return C; else { token [i-st] = str [i]; i++; } } token [i-st] = '\0'; i++; return i; } int convert (char*str) { int i = 1; int num; num = str [i] - '0'; while (str [i] != '\0') { num = num * 10; num = num + str [i] - '0'; i++; } return '\0'; }



LinkBack URL
About LinkBacks


