This is a c++ code to evaluate an infix expression.My code gives the correct output when I put an infix expression directly in the code but when I take an expression from the user and then pass that expression, the code does not give a correct answer, I am not being able to understand why.I have used my custom stack file. If you could kindly find my mistake and fix my code. Thank you.
#include <iostream>
#include"stacklink.h"
#include"stacklink.cpp"
#include<bits/stdc++.h>
using namespace std;
int precedence(char op){
if(op == '+'||op == '-')
return 1;
if(op == '*'||op == '/')
return 2;
return 0;
}
int applyOp(int a, int b, char op){
switch(op){
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
int evaluate(string tokens){
int i;
StackType <int> values;
StackType <char> ops;
for(i = 0; i < tokens.length(); i++){
if(tokens[i] == ' ')
continue;
else if(tokens[i] == '('){
ops.Push(tokens[i]);
}
else if(isdigit(tokens[i])){
int val = 0;
while(i < tokens.length() &&
isdigit(tokens[i]))
{
val = (val*10) + (tokens[i]-'0');
i++;
}
values.Push(val);
}
else if(tokens[i] == ')')
{
while(!ops.IsEmpty() && ops.Top() != '(')
{
int val2 = values.Top();
values.Pop();
int val1 = values.Top();
values.Pop();
char op = ops.Top();
ops.Pop();
values.Push(applyOp(val1, val2, op));
}
if(!ops.IsEmpty())
ops.Pop();
}
else
{
while((!ops.IsEmpty()) && precedence(ops.Top())
>= precedence(tokens[i])) {
int val2 = values.Top();
values.Pop();
int val1 = values.Top();
values.Pop();
char op = ops.Top();
ops.Pop();
values.Push(applyOp(val1, val2, op));
}
ops.Push(tokens[i]);
}
}
while(!ops.IsEmpty()){
int val2 = values.Top();
values.Pop();
int val1 = values.Top();
values.Pop();
char op = ops.Top();
ops.Pop();
values.Push(applyOp(val1, val2, op));
}
return values.Top();
}
int main() {
//cout << evaluate("10 + 2 * 6") << "\n";
//cout << evaluate("10 + 3 * 5 / ( 16 - 4 )") << "\n";
//cout << evaluate("100 * ( 2 + 12 )") << "\n";
//cout << evaluate("100 * ( 2 + 12 ) / 14");
string infix;
cin>>infix;
cout<< evaluate(infix);
return 0;
}
Instead of using cin>>infix use getline(cin,infix) Because in case of cin It will take input till a ' ' or '\n' or '\t' and your string contains blank spaces so it is reading till black space Lets say your expression is 10 + 2 but it is reading expression as only 10 . But if you will use getline then it will read whole line till "\n".
Hope It may Help....!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.