I have a file that contains text in RPN, each line is different. Let's take first line for example:
12 2 3 4 * 10 5 / + * +
I need to count a total of each line. To do so, I need to use stack. It works like this: If there's a number -> add it to stack, if it's +,-,* or / -> take two newest numbers on stack and do said operation on them.
The problem is, I got stuck at the moment of reading the file. I was thinking about storing the numbers and signs in an array, but I've got another problem here:
If (array is storing chars):
array[0] = '1',
array[1] = '2',
array[2] = ' ',
how do I make it into int 12 (space means it's the end of a number)? Is there an easy and short way to do so? Or maybe there's a better way to read the file and put it on stack?
Thanks to suggestions about using strings to store the data, I made it, here is the implementation:
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
using namespace std;
int main(){
stack <int> stos;//the name is a bit weird but it's just 'stack' in polish
ifstream in("Test1.txt");//opening file to read from
string linia;//again - "linia" is just "line" in polish
int i = 1;//gonna use that to count which line i'm in
while (getline(in, linia, ' ')){
if (linia == "*"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
stos.push(a*b);
}
else if (linia == "+"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
stos.push(a+b);
}
else if (linia == "-"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
stos.push(a-b);
}
else if (linia == "/" || linia == "%"){
int b = stos.top();
stos.pop();
int a = stos.top();
stos.pop();
int c = a / b;
stos.push(c);
}
else if (linia == "\n"){
cout << "Wynik nr " << i << ": " << stos.top() << endl;
stos.pop();
i++;
}
else{//if it's a number
stos.push(atoi(linia.c_str()));
}
}
}
The file looks like this:
12 2 3 4 * 10 5 / + * +
2 7 + 3 / 14 3 - 4 * +
The space before each line that isn't the first line is necessary, otherwise the program will take "\n" together with the first number of the next line, which we don't want.