Last active
July 2, 2019 18:52
-
-
Save djpeach/40259087d182708a0612a6e6d5144c1c to your computer and use it in GitHub Desktop.
This file contains 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 <iostream> | |
#include <queue> | |
#include <cctype> | |
int main (int argc, char *argv[]) { | |
if (argc < 2) { | |
std::cout << "please provide an expression" << std::endl; | |
return -1; | |
} | |
char *expression = argv[1]; | |
int expLength = strlen(argv[1]); | |
std::queue<char> operands; | |
std::queue<char> operators; | |
for(int i=0;i<expLength;i++) { | |
switch(expression[i]) { | |
case '+': case '-': | |
operators.push(expression[i]); | |
break; | |
default: | |
if (isdigit(expression[i])) { | |
int operand = (int)(expression[i] - '0'); | |
operands.push(operand); | |
} else { | |
std::cout << "I don't know what to do with " << expression[i] << std::endl; | |
return -1; | |
} | |
break; | |
} | |
} | |
int result = operands.front(); | |
operands.pop(); | |
while(!operators.empty()) { | |
int nextOperand = operands.front(); | |
operands.pop(); | |
switch (operators.front()) { | |
case '+': | |
result += nextOperand; | |
break; | |
case '-': | |
result -= nextOperand; | |
break; | |
default: | |
std::cout << "This operator: " << operators.front() << " should not be here" << std::endl; | |
return -1; | |
break; | |
} | |
operators.pop(); | |
} | |
std::cout << argv[1] << " = " << result << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment