calculator - Splitting calculations in a stack C++ -
i trying learn c++. have created calculator allows 1 line text input, splits string , performs calculation depending on operator.
syntax 5*2 of course return 10.
next step allow multiple operators in same line i.e. 5*2/4
advise on how might this? imagine looping or push/pop have no idea route work best.
understand there many calculators such reverse polish notation wondered if me 1 in particular. thanks.
#include <iostream> using namespace std; int main() { while (true) { string str; float eq1; float eq2; cout << "request: " << flush; cin >> str; if (str.find('/') != string::npos) { int pos = str.find("/"); string sub1 = str.substr(0, pos); eq1 = stof(sub1); string sub2 = str.substr(pos + 1); eq2 = stof(sub2); cout << eq1 / eq2 << endl; } else if (str.find('*') != string::npos) { int pos = str.find("*"); string sub1 = str.substr(0, pos); eq1 = stof(sub1); string sub2 = str.substr(pos + 1); eq2 = stof(sub2); cout << eq1 * eq2 << endl; } else if (str.find('-') != string::npos) { int pos = str.find("-"); string sub1 = str.substr(0, pos); eq1 = stof(sub1); string sub2 = str.substr(pos + 1); eq2 = stof(sub2); cout << eq1 - eq2 << endl; } else if (str.find('+') != string::npos) { int pos = str.find("+"); string sub1 = str.substr(0, pos); eq1 = stof(sub1); string sub2 = str.substr(pos + 1); eq2 = stof(sub2); cout << eq1 + eq2 << endl; } } }
the general method take string whole , separate operators (*, /, +, -, etc.) operands (the numbers). making 2 stacks , inserting operators 1 stack , operands other. in calculation phase, pop 2 operands , pop 1 operator , calculation. keep doing until both stacks empty. luck!
Comments
Post a Comment