Reputation: 639
I'm trying to write a post-fix/reverse polish calculator, only that before each number, there will be a '#', before each operator, a '!', and a '.' to signify the end of the expression. One space between each number/character/etc. I don't care about error-checking.
I understand that you can use stringstream here, but I still think that it should be able to work without it.
The input, entered into the console, would look something like,
# 33 # 3 ! / # 2 ! *.
which would then output 22. I am currently getting a segmentation fault with the below code.
Thanks for looking.
#include <iostream>
#include <cstdlib>
#include <math.h>
using namespace std;
class Stack{
public:
Stack(){
this->size = 0;
}
Stack & push(double c){
if (size == MAX_SIZE) die("Push Overflow");
data[size] = c;
size++;
return *this;
}
double pop(){
return data[--size];
}
double top() const{
return data[size-1];
}
unsigned getSize() const{return size;}
bool die(const string & msg){
cerr << "Fatal Error: " << msg << endl;
exit(EXIT_FAILURE);
}
void show(){
for (int i = 0; i < size; i++){
cout << data[i] << endl;
}}
private:
static const unsigned MAX_SIZE = 50;
double data[MAX_SIZE];
unsigned size;
};
int main(){
Stack s1;
bool inputComplete = false;
double num1 =0;
double num2 = 0;
double answer = 0;
char c, ch;
while(!inputComplete){
cin >> ch;
if (ch == '!'){
cin >> c;
num1 = s1.pop();
num2 = s1.pop();
switch(c){
case '+':
answer = num2 + num1;
break;
case '-':
answer = num2 - num1;
break;
case '/':
answer = num2/num1;
break;
case '^':
answer = pow(num2, num1);
break;
case '*':
answer = num2 * num1;
break;
}
s1.push(answer);
}
else if (c == '#'){
double number;
cin >> number;
s1.push(number);
}
else if (c == '.'){
inputComplete == true;
}
}
s1.show();
return 0;
}
Upvotes: 1
Views: 137
Reputation: 206667
Problems I found:
The line
else if (c == '#'){
should be
else if (ch == '#'){
The line
else if (c == '.'){
should be
else if (ch == '.'){
The line
inputComplete == true;
should be
inputComplete = true;
Update
I realize that you don't want any error checking code. But a minimal amount of error checking is useful. To that end, I think you should check when EOF is reached.
ch = cin.get();
if ( ch == EOF )
{
inputComplete = true;
}
else if (ch == '!'){
instead of
cin >> ch;
if (ch == '!'){
makes sense to me.
Upvotes: 2
Reputation: 12047
At the end there is
else if (c == '.'){
inputComplete == true;
}
but it should be
else if (c == '.'){
inputComplete = true;
}
Upvotes: 1