My rpn-calculator works, but it has a problem. The problem is that it prints out every consecutive calculation that it makes along the way.
I have tried different ways of fixing this, the latest one being adding an integer that goes up by every calculation and a printf that prints if this integer is above 0 as well as there only being one number on the stack.
However, this causes problems when there is more than one calculation going on (for example writing 5 5 + 10 5 * *) will cause 10 500 being printed out because there is only one item on the stack after the first calculation.
How can I solve this?
#define MAX_STACK_SIZE 100
#define MAX_BUFFER_SIZE 100
char buff[MAX_BUFFER_SIZE];
double x, stack[MAX_STACK_SIZE];
double t;
int i, k=0, num_operand=0;
int main(void) {
while(x != 'q') {
if( scanf("%s", buff) < 1 )
{ return 0;
}
if(isdigit(buff[0]) || isdigit(buff[1])) {
sscanf(buff, "%lf", &x);
if (num_operand < MAX_STACK_SIZE)
{
stack[num_operand]=x;
num_operand ++;
} else { printf("Make stack bigger\n");}
} else {
switch(buff[0]) {
case '+': stack[num_operand - 2] = stack[num_operand - 1] + stack[num_operand - 2];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '-': stack[num_operand - 2] = stack[num_operand - 2] - stack[num_operand - 1];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '/': stack[num_operand - 2] = stack[num_operand - 2] / stack[num_operand - 1];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
case '*': stack[num_operand - 2] = stack[num_operand - 1] * stack[num_operand - 2];
num_operand --;
num_operand --;
t = stack[num_operand];
k++;
num_operand ++;
break;
} }
if (num_operand == 1 && k !=0) {
k = 0;
printf("%lf \n", t); }
}
}
"%s"
consumes leading white-spaces like' '
and'\n'
alike - so the distinction between end of line and the space separator is lost.To distinguish between lines of input use
fgets()
and process the line. Then print the result. @molbdniloIt test for
q
, code needs to test the textual contents of the line, notdouble x
. @BLUEPIXY