#include"hw3.h" #include<iomanip.h> const char bottom = '['; const char lpar = '('; const char rpar = ')'; const char plus = '+'; const char minus = '-'; const char unaryminus = '~'; const char times = '*'; const char by = '/'; bool processnumber(stackintorchar&parsestack,int n) { intorchar top1; intorchar top2; top1 = parsestack.pop(); if(top1 == plus); { top2 = parsestack.pop(); if (top2 == number) { parsestack.push(top2+n); return true; } else return false; } if(top1 == minus) { top2 = parsestack.pop(); if (top2 == number) { parsestack.push(top2-n); return true; } else return false; } else if (top1 == unaryminus) { parsestack.push(-n); return true; } else if (top1 == bottom || top1 == lpar) { parsestack.push(top1); parsestack.push(n); return true; } else return false; } bool processlpar(stackintorchar&parsestack) { parsestack.push(lpar); return true; } bool processrpar(stack1ntorchar&parsestack) { intorchar top1; top1 = parsestack.pop(); if(top1 == number) if (parsestack.isempty()) return false; else { intorchar top2; top2 = parsestack.pop(); if(top2 == lpar) { processnumber(parsestack,top1+0); return true; } else return false; } else return false; } bool processplus(stackintorchar&parsestack) { parsestack.push(plus); return true; } bool processminus(stackintorchar&parsestack) { intorchar top1; top1 = parsestack.pop(); parsestack.push(top1); if(top1 == lpar || top1 == bottom) parsestack.push(unaryminus); else parsestack.push(minus); return true; } bool processeoln(stackintorchar&parsestack) { intorchar top1; intorchar top2; top1 = parsestack.pop(); if(top1 == number) { top2 = parsestack.pop(); if(top2 == bottom) { parsestack.push(top1); return true; } else return false; } else return false; } int val(char c) { return (int)c - (int)'0'; } bool onecharok(stackintorchar&parsestack,char newchar) { if(newchar >= '0' && newchar <= '9') return processnumber(parsestack,val(newchar)); else if (newchar == lpar) return processlpar(parsestack); else if (newchar == rpar) return processrpar(parsestack); else if (newchar == plus) return processplus(parsestack); else if (newchar == minus) return processminus(parsestack); else return false; } bool accept(stackintorchar&parsestack) { bool acceptablesofar = true; char newchar; newchar=cin.get(); while(acceptablesofar && newchar!='\n' && !cin.eof()) { acceptablesofar = onecharok(parsestack,newchar); newchar=cin.get(); } if (acceptablesofar) acceptablesofar = processeoln(parsestack); return acceptablesofar; } int main() { stackintorchar parsestack; parsestack.push(bottom); if (accept(parsestack)) cout << "The value of the expression is " << parsestack.pop() << endl; else cout << "The input string is not a valid expression" << endl; return 0; }