Skip to content

Commit

Permalink
calculator: add implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
gannicus309 committed Jul 20, 2020
1 parent 29db33e commit 2bce0cf
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 6 deletions.
67 changes: 64 additions & 3 deletions calculator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,69 @@

namespace dev {

double Calculator::evaluate(std::string expression) {
return 0;
bool Calculator::IsOperator(char c){
switch (c){
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false;
}
}

} // namespace calculator
double Calculator::evaluate(std::string expression)
{
double ret =0.0;
float v1,v2;
v1=v2=0;
for(int i=0;i < expression.length();i++)
{
if (isspace(expression[i])){
continue;
}

if(isdigit(expression[i]))
{
std::string str(1,expression[i]);
mStack.push(std::stof(str));
}
else if (IsOperator(expression[i])){
if (expression[i] == '+'){
v1 = mStack.top();
mStack.pop();
v2 = mStack.top();
mStack.pop();
ret = v1+v2;
}
if (expression[i] == '-'){
v1 = mStack.top();
mStack.pop();
v2 = mStack.top();
mStack.pop();
ret = v1-v2;
}
if (expression[i] == '*'){
v1 = mStack.top();
mStack.pop();
v2 = mStack.top();
mStack.pop();
ret = v1*v2;
}
if (expression[i] == '/'){
v1 = mStack.top();
mStack.pop();
v2 = mStack.top();
mStack.pop();
ret = v2/v1;
}

mStack.push(ret);
}
}
//Return answer
return mStack.top();
}

} // namespace dev
7 changes: 5 additions & 2 deletions calculator.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#include<string>

#include<stack>
namespace dev {

class Calculator {
Expand All @@ -8,7 +8,10 @@ class Calculator {
~Calculator() = default;

double evaluate(std::string expression);


private:
std::stack<float> mStack;
bool IsOperator(char c);
};

} // namespace calculator
7 changes: 6 additions & 1 deletion project.cc
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
#include<iostream>
#include "project.h"
#include "calculator.h"
namespace dev {

int Project::run() {
Calculator calc;
calc.evaluate("2 3 +");
std::string s;
std::cout<<"enter the string: ";
std::getline(std::cin,s);

std::cout<<"Result:"<<calc.evaluate(s)<<std::endl;
return 0;
}
} // namespace dev

0 comments on commit 2bce0cf

Please sign in to comment.