Was reading the other thread on a basic calculator and started making one myself just for some practice. The problem I had was checking for valid types.
It works perfectly, but if you pass alpha strings into varA and varB it will still calculate them since the stringstream turns them into int form. This isn't really a problem, but I would rather have it reject alpha chars for these vars.Code:#include <iostream> #include <string> #include <math.h> #include <sstream> using namespace std; class calcIt { int varA, varB; public: calcIt() { varA=0; varB=0; }; int addIt(int addOne, int addTwo) { return (addOne + addTwo); }; int subIt(int subOne, int subTwo) { return (subOne - subTwo); }; int mulIt(int mulOne, int mulTwo) { return (mulOne * mulTwo); }; int divIt(int divOne, int divTwo) { return (divOne / divTwo); }; int checkNum(int checkN); }; int calcIt::checkNum(int checkN) { if (fmod(checkN, 1) == 0) { return checkN; } return -1; } int main() { int varA, varB, firstW, secondW; string varC; calcIt c; cout << "Enter the calculation to be made ( n +/-* n ) : "; getline(cin, varC); firstW = varC.find(" ",0); secondW = varC.find(" ", (firstW + 1)); stringstream(varC.substr(0, firstW)) >> varA; stringstream(varC.substr(secondW)) >> varB; varC = varC.substr((firstW + 1), 1); if (( c.checkNum(varA) == -1 ) || ( c.checkNum(varB) == -1)) { cout << endl << "Invalid operators!" << endl; return 1; } if (varC == "*") { cout << endl << c.mulIt(varA,varB) << endl; } else if(varC == "/") { cout << endl << c.divIt(varA,varB) << endl; } else if(varC == "+") { cout << endl << c.addIt(varA,varB) << endl; } else if(varC == "-") { cout << endl << c.subIt(varA,varB) << endl; } else { cout << endl << "Invalid operator!" << endl; } return 0; }



LinkBack URL
About LinkBacks



