Need to fix my code

The point of the code is to make an RPN calculator. Everything seems to be working fine, except for my "quit" and "clear" commands. Whenever q or c is entered the code stops working. Any advice is appreciated. Here is my source code.

#include <iostream>;
#include <stack>;
#include <string>;
#include <sstream>;

using namespace std;

bool OperandCheck(string input);
double PerformOp(stack<double>& theStack, const string input);



int main()
{
stack<double> theStack;
string input;



cout << "Welcome to RPN Calculator. Enter q to quit. Enter c to clear." << endl;
while (true)
{
cout << ">>";
cin >> input;

double num;

if (istringstream(input) >> num)
{
theStack.push(num);
}
else if (OperandCheck(input))
{
PerformOp(theStack, input);
}
else if (input == "q")
{
cout << "Program Ended." << endl;
return 0;
}
else if (input == "c")
{
while (!theStack.empty())
{
theStack.pop();
}
}
else
{
cout << "Invalid Input." << endl;
}


}
return 0;
}
bool OperandCheck(const string input)
{
string Operand[] = { "+", "-", "*", "/" };
for (int i = 0; i <= 4; i++)
{
if (input == Operand[i])
{
return true;
}
}
return false;
}
double PerformOp(stack<double>& theStack, const string input)
{
double rVal;
double lVal;
double result;
rVal = theStack.top();
theStack.pop();
lVal = theStack.top();
theStack.pop();

if (input == "+")
{
result = lVal + rVal;
}
else if (input == "+")
{
result = lVal - rVal;
}
else if (input == "*")
{
result = lVal * rVal;
}
else
{
result = lVal / rVal;
}
cout << result << endl;
theStack.push(result);
return 0;
}

> Whenever q or c is entered the code stops working.
you need to be more descriptive
also, provide an example input.


1
2
3
bool OperandCheck(const string input) {
	string Operand[] = {"+", "-", "*", "/"};
	for(int i = 0; i <= 4; i++) {
¿how many times would that loop?
Last edited on
closed account (48T7M4Gy)
@OP

Please use code tags. Go back and select the code and press <> in the toolbar on the right.

I tried your code and it runs OK via q and c input.

A couple of things:
1. #include's aren't followed by a ';'
2. You have 2 if input == '+' statements when the second should be '-'
3. It's a good idea to have an if statement in the '/' part for the 0 divisor case
Topic archived. No new replies allowed.