I am working on a reverse polish notation calculater. It works for one set of data, however i cant seem to figure out how to make it work if there is more than one row of data to use. for example, if the text file looks like this:
3 4 5 + -
4 3 2 * -
1 2 4 5 - + +
how would i get it to stop reading after the end of the first line so that i could reset everything and start anew for the second set of data?
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <fstream>
#include <stack>
usingnamespace std;
int pop(vector<int>& stk);
ifstream indata;
int main() {
indata.open("testfile.txt"); //opens the test file
if (!indata) {
cerr << "Unable to open file testfile.txt"; //check to see if testfile.txt was found
}
vector<int> Stack;
string input; // to read number or operator
while (!indata.eof()) {
indata>>input;
if (isdigit(input[0])) { // if first is digit, it's number.
Stack.push_back(atoi(input.c_str())); // convert, push
} else { // If it's not a number, assume it's an operator
int first, second;
switch (input[0]) {
case'+': Stack.push_back(pop(Stack) + pop(Stack));
break;
case'-': second = pop(Stack);
first = pop(Stack);
Stack.push_back(first - second);
break;
case'*': Stack.push_back(pop(Stack) * pop(Stack));
break;
case'/': second = pop(Stack);
first = pop(Stack);
Stack.push_back(first/ second);
break;
case'/n': cout<<"this";
default: throw domain_error("Undefined operator");
}
cout << "Result: " << Stack.back() << endl;
}
}
return 0;
}
int pop(vector<int>& stk) {
if (stk.empty()) {
throw underflow_error("Stack underflow.");
}
int result = stk.back();
stk.pop_back();
return result;
}
i know its something simple, ive just been staring at the code for way too long and cant think.. lol