I am trying to write a RPN calculator in which this line of input for a simple example: 2 3 + would print: 5 and then end.
I need the program to take the line of input, put the numbers on the stack, find non-numbers, check if they are operators: '+', '-', '/', or '*' and if they are then they compute the calculation for the last two numbers on the stack, remove those two numbers, and then add the new number onto the stack. This needs to go left to right, parsing through the line of input. Also if the symbol is not one of the operators it should print to cout.
Currently the program dumps a very long list of error code onto the screen when compiling.
Here is what I have:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
stack<int> num;
string line;
int n,count=0,a,b;
char c;
while (getline(cin,line))
{
for (string::const_iterator it = line.begin(); it != line.end(); ++ it)
{
if (isdigit(static_cast<unsigned char>(*it)))
{
cout << it << endl;
n = (it - 48);
num.push(n);
count++;
}
else if (ispunct(static_cast<unsigned char>(*it)))
{
if (it == '+' || it == '-' || it == '/' || it == '*')
{
cout << "count is " << count << endl;
if (count>1)
{
b = num.top();
num.pop();
a = num.top();
num.pop();
if (it == '+')
{
cout << "+" <<endl;
num.push(a+b);
count--;
}
else if (it == '-')
{
num.push(a-b);
count--;
}
else if (it == '/')
{
if (b != 0)
{
num.push(a/b);
count--;
}
else
{
cout << "division by zero" << endl;
return(0);
}
}
else if (it == '*')
{
num.push(a*b);
count--;
}
else
{
cout << "invalid input" << endl;
return(0);
}
}
else
{
cout << "stack underflow" << c << endl;
return(0);
}
}
cout << c << endl;
}
}
}
while ( !num.empty() )
{
cout << num.top() << endl;
num.pop();
}
return 0;
}
You're missing the dereference operator (the asterisk) on most your uses of it
.
And you're using c
uninitialized.
And don't forget to add the <cctype
header for isdigit
and ispunct
.