Skip to content

Commit ae8d9f4

Browse files
committed
Fixed bug, was not exiting with status 0 if the expression was invalid
1 parent 7e2a91c commit ae8d9f4

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44
# generated directories
55
bin/
66
obj/
7-
*.exe
7+
*.exe
8+
.vscode

main.cpp

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,11 @@ int main(int argc, char **argv) {
5151
}
5252

5353
void manageFirstBracketAfterOperand(vector<string> &tokens) {
54+
// cout << "Manage first bracket" << endl;
55+
if(tokens.size() == 0)
56+
return;
5457
string multiplySign = "*";
58+
if(tokens.size() == 0) return;
5559
for (int i = 0; i < tokens.size() - 1; i++) {
5660
if (isOperand(tokens[i]) && tokens[i + 1] == "(") {
5761
i++;
@@ -60,6 +64,9 @@ void manageFirstBracketAfterOperand(vector<string> &tokens) {
6064
}
6165
}
6266
void manageLeadingNegativeSign(vector<string> &tokens) {
67+
// cout << "Manage Leading Negative Sign" << endl;
68+
if(tokens.size() == 0)
69+
return;
6370
string openBracket = "(";
6471
string closeBracket = ")";
6572
string zero = "0";
@@ -104,6 +111,7 @@ double eval(string &exp) { return eval(exp, 0); }
104111

105112
double eval(string &exp, double x) {
106113
vector<string> tokens = breakIntoTokens(exp);
114+
// if(tokens.size() == 0) return -1;
107115
manageFirstBracketAfterOperand(tokens);
108116
manageLeadingNegativeSign(tokens);
109117
tokens = convertToPostfixExp(tokens);
@@ -119,18 +127,19 @@ double eval(string &exp, double x) {
119127
excStack.push(operation(op1, op2, token));
120128
}
121129
}
122-
return excStack.top();
123-
return 0;
130+
return excStack.empty() ? -1 : excStack.top();
124131
}
125132
vector<string> breakIntoTokens(string &exp) {
133+
// cout << "Breaking Into Tokens" << endl;
134+
126135
vector<string> tokens;
127136
string currentToken = "";
128137

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

132141
if (!isValidCharacter(ch)) {
133-
cout << dye::light_red("Invalid Expression");
142+
cout << dye::light_red("Invalid Expression ");
134143
return tokens;
135144
}
136145

@@ -151,9 +160,11 @@ vector<string> breakIntoTokens(string &exp) {
151160
return tokens;
152161
}
153162
vector<string> convertToPostfixExp(vector<string> &tokens) {
163+
// cout << "Convert to postfix" << endl;
154164
vector<string> postfix;
155165
stack<string> stk;
156-
166+
if(tokens.size() == 0)
167+
return tokens;
157168
for (auto &token : tokens) {
158169
if (isOperand(token))
159170
postfix.push_back(token);

0 commit comments

Comments
 (0)