Last active
December 29, 2015 15:39
-
-
Save vczh/7692612 to your computer and use it in GitHub Desktop.
Simple Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "calc.h" | |
bool Char(const char*& input, char c) | |
{ | |
if(*input==c) | |
{ | |
input++; | |
return true; | |
} | |
return false; | |
} | |
bool Int(const char*& input, int& result) | |
{ | |
int sign=1; | |
while(Char(input, '-')) sign*=-1; | |
char* endptr=0; | |
result=strtol(input, &endptr, 10); | |
if(input==endptr) return false; | |
result*=sign; | |
input=endptr; | |
return true; | |
} | |
bool Factor(const char*& input, int& result) | |
{ | |
if(Int(input, result)) return true; | |
if(!Char(input, '(')) return false; | |
if(!Exp(input, result)) return false; | |
if(!Char(input, ')')) return false; | |
return true; | |
} | |
bool Term(const char*& input, int& result) | |
{ | |
if(!Factor(input, result)) return false; | |
while(true) | |
{ | |
int op=0; | |
if(Char(input, '*')) | |
{ | |
if(!Factor(input, op)) return false; | |
result*=op; | |
} | |
else if(Char(input, '/')) | |
{ | |
if(!Factor(input, op)) return false; | |
result/=op; | |
} | |
else return true; | |
} | |
} | |
bool Exp(const char*& input, int& result) | |
{ | |
if(!Term(input, result)) return false; | |
while(true) | |
{ | |
int op=0; | |
if(Char(input, '+')) | |
{ | |
if(!Term(input, op)) return false; | |
result+=op; | |
} | |
else if(Char(input, '-')) | |
{ | |
if(!Term(input, op)) return false; | |
result-=op; | |
} | |
else return true; | |
} | |
} | |
bool Calculate(const string& expr, int& result) | |
{ | |
const char* input=expr.c_str(); | |
return Exp(input, result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment