I want to be able to evaluate an expression typed by the user (ie 23+5-4, 23-4-5, 2+5+6+7 etc...any length). The expression contains only integers, '+', and '-' (no parentheses). I have worked on the following for a hours now...it crashes when I run it after it prompts for the input. I do not know what is wrong. Can anyone tell me what is wrong with my code ( I am programming in VC++ --which later I have to make g++ compatible). Thanks very much. -chanthee
(You must forgive me if this looks ugly...but I don't know how to set tags...I've never posted before)
Code:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cctype>
#include <stack>
using namespace std;
int read_and_evaluate(istream& ins);
void evaluate_expression(stack<int>& numbers, char& symbol);
int main()
{ int answer;
cout << "Enter an arithmetic expression: "<< endl;
answer = read_and_evaluate(cin);
cout << "The answer is "<< answer << endl;
return EXIT_SUCCESS;
}
int read_and_evaluate(istream& ins)
{
stack<int> numbers;
int number;
char symbol;
do
{
if (isdigit(ins.peek()))
{
ins >> number;
numbers.push(number);
}
else
{
ins >> symbol;
evaluate_expression( numbers, symbol);
}
}
while (ins && ins.peek() != '\n');
return numbers.top();
}
void evaluate_expression(stack<int>& numbers, char& symbol)
{
int operand2, operand1;
operand2 = numbers.top();
numbers.pop();
operand1 = numbers.top();
numbers.pop();
switch(symbol)
{
case '+': numbers.push(operand1 + operand2);
break;
case '-': numbers.push(operand1 - operand2);
break;
}
}
Code tags added by Kermi3