Skip to content

Commit

Permalink
Fixed bug, was not exiting with status 0 if the expression was invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
codeAbinash committed Dec 20, 2022
1 parent 7e2a91c commit ae8d9f4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
# generated directories
bin/
obj/
*.exe
*.exe
.vscode
19 changes: 15 additions & 4 deletions main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ int main(int argc, char **argv) {
}

void manageFirstBracketAfterOperand(vector<string> &tokens) {
// cout << "Manage first bracket" << endl;
if(tokens.size() == 0)
return;
string multiplySign = "*";
if(tokens.size() == 0) return;
for (int i = 0; i < tokens.size() - 1; i++) {
if (isOperand(tokens[i]) && tokens[i + 1] == "(") {
i++;
Expand All @@ -60,6 +64,9 @@ void manageFirstBracketAfterOperand(vector<string> &tokens) {
}
}
void manageLeadingNegativeSign(vector<string> &tokens) {
// cout << "Manage Leading Negative Sign" << endl;
if(tokens.size() == 0)
return;
string openBracket = "(";
string closeBracket = ")";
string zero = "0";
Expand Down Expand Up @@ -104,6 +111,7 @@ double eval(string &exp) { return eval(exp, 0); }

double eval(string &exp, double x) {
vector<string> tokens = breakIntoTokens(exp);
// if(tokens.size() == 0) return -1;
manageFirstBracketAfterOperand(tokens);
manageLeadingNegativeSign(tokens);
tokens = convertToPostfixExp(tokens);
Expand All @@ -119,18 +127,19 @@ double eval(string &exp, double x) {
excStack.push(operation(op1, op2, token));
}
}
return excStack.top();
return 0;
return excStack.empty() ? -1 : excStack.top();
}
vector<string> breakIntoTokens(string &exp) {
// cout << "Breaking Into Tokens" << endl;

vector<string> tokens;
string currentToken = "";

for (char &ch : exp) {
if (ch == ' ' || ch == '\n' || ch == '\t') continue;

if (!isValidCharacter(ch)) {
cout << dye::light_red("Invalid Expression");
cout << dye::light_red("Invalid Expression ");
return tokens;
}

Expand All @@ -151,9 +160,11 @@ vector<string> breakIntoTokens(string &exp) {
return tokens;
}
vector<string> convertToPostfixExp(vector<string> &tokens) {
// cout << "Convert to postfix" << endl;
vector<string> postfix;
stack<string> stk;

if(tokens.size() == 0)
return tokens;
for (auto &token : tokens) {
if (isOperand(token))
postfix.push_back(token);
Expand Down

0 comments on commit ae8d9f4

Please sign in to comment.