Skip to content

Commit

Permalink
calculator: add implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
gannicus309 authored and Ganesh Rengasamy committed Jul 21, 2020
1 parent 29db33e commit 0150f47
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 8 deletions.
75 changes: 72 additions & 3 deletions calculator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,77 @@

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;

while (i < expression.size() && ((isdigit(expression[i]) || expression[i] == '.')))
{
str.push_back(expression[i]);
i++;
}

mStack.push(stof(str));
i--;
}
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 = v2-v1;
}
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
10 changes: 10 additions & 0 deletions main.cc
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
#include "run.h"
#include "project.h"
#include "calculator.h"
#include<iostream>

int main() {

dev::Calculator calc;
std::string s;
std::cout<<"enter the string: ";
std::getline(std::cin,s);

std::cout<<"Result:"<<calc.evaluate(s)<<std::endl;

dev::Project p;
return run(p);
}
3 changes: 0 additions & 3 deletions project.cc
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
#include "project.h"
#include "calculator.h"
namespace dev {

int Project::run() {
Calculator calc;
calc.evaluate("2 3 +");
return 0;
}
} // namespace dev

0 comments on commit 0150f47

Please sign in to comment.