I guess some of you are familiar with the Reverse Polish Notation implemented through a stack. We were tasked to create a program automating such. I get the essence of the problem but I'm having trouble with the input. Also, my code is not compiling.
Here's the specifcations
Input Format
The input starts with an integer N, where 0 = N < 1000. The next N lines consists of artithmetic expressions in RPN. The expressions only involve the operations +, -, *, / and integer values.
Output Format
For every input line, output the corresponding RPN evaluation. If ever a division by zero occurs, output the message UNDEFINED immediately.
Sample Input
3
4 5 +
3 2 / 4 3 - +
2 0 /
Sample Output
9
2
UNDEFINED
I can't decide what algorithm to use in parsing the input and I eventually used stringstream. I am not sure though if I used it right.
#include <iostream>
#include <stack>
#include <cstdlib>
#include <string>
#include <sstream>
#include <cstring>
#include <cctype>
usingnamespace std;
int main()
{
stack <int> s;
int N, i = 0;
bool undefined;
string dummy;
cin >> N;
getline(cin, dummy);
int a, b;
string sequence;
string tokens;
while (i < N)
{
getline(cin, sequence);
stringstream sin(sequence);
undefined = false;
while (sin >> tokens)
{
if (isdigit(tokens[0]))
s.push(atoi(tokens.c_str()));
else
{
switch(tokens[0])
{
case'+':
b = s.top();
s.pop();
a = s.top();
s.pop();
s.push(a+b);
case'-':
b = s.top();
s.pop();
a = s.top();
s.pop();
s.push(a-b);
case'*':
b = s.top();
s.pop();
a = s.top();
s.pop();
s.push(a*b);
case'/':
b = s.top();
s.pop();
if (b == 0)
undefined = true;
else
{
a = s.top();
s.pop();
s.push(a / b);
}
}
}
}
if (undefined)
cout << "UNDEFINED" << endl;
else
{
cout << s.top() << endl;
s.pop();
}
i++;
}
return 0;
}
I am also not sure if I used the isdigit() under cctype library correct. Any suggestions on how I can input successfully and compile the code? If you think sstream can't do the job, what alternatives can I use? Thanks in advance.