diff --git a/calculator.cc b/calculator.cc index 77a5804..232e776 100644 --- a/calculator.cc +++ b/calculator.cc @@ -21,10 +21,12 @@ double Calculator::evaluate(std::string expression) v1=v2=0; for(int i=0;i < expression.length();i++) { + // ignore the spaces if (isspace(expression[i])){ continue; } + // Push to stack, if digit if(isdigit(expression[i])) { std::string str; @@ -36,8 +38,10 @@ double Calculator::evaluate(std::string expression) } mStack.push(stof(str)); + // Decrease index as currently points to advanced element i--; } + // Check if operator and perform the operation of numbers from stack else if (IsOperator(expression[i])){ if (expression[i] == '+'){ v1 = mStack.top(); @@ -68,10 +72,11 @@ double Calculator::evaluate(std::string expression) ret = v2/v1; } + // push the final result mStack.push(ret); } } - //Return answer + // return answer return mStack.top(); } diff --git a/calculator.h b/calculator.h index d191725..63a4ed6 100644 --- a/calculator.h +++ b/calculator.h @@ -7,9 +7,14 @@ class Calculator { Calculator() = default; ~Calculator() = default; + /** + * method to evaluate the expression + */ double evaluate(std::string expression); private: + + //Stack to hold the numbers std::stack mStack; bool IsOperator(char c); }; diff --git a/main.cc b/main.cc index 3594508..ba5bd96 100644 --- a/main.cc +++ b/main.cc @@ -7,9 +7,8 @@ int main() { dev::Calculator calc; std::string s; - std::cout<<"enter the string: "; + std::cout<<"Enter the string: "; std::getline(std::cin,s); - std::cout<<"Result:"<