Generation

generate functionMon, 09 Jan 2023

The slides for Week 8 show a reverse-Polish notation calculator. An example session, that calculates 1+2×3+4, might be as follows: $ ./calc 1 2 3 * 4 + + 11 Modify the calculator so that it uses scanf() to read numbers and operators. This should allow you to omit the space after numbers in your expressions, but if you find that you still need to read one character too much from the input then also use ungetc() to push the ‘one character too much’ back onto the standard input. int main() { char line[32]; for (;;) { int c = getop(line, sizeof(line)); if (c < 0) break; switch (c) { case 0: while (depth) printf("=> %g\n", pop()); break; case NUMBER: push(atod(line)); break; case '+': { double r = pop(), l = pop(); push(l + r); } break; case '-': { double r = pop(), l = pop(); push(l - r); } break; case '*': { double r = pop(), l = pop(); push(l * r); } break; case '/': { double r = pop(), l = pop(); push(l / r); } break; case '%': { double r = pop(), l = pop(); push(l - r*(int)(l/r)); } break; default: printf("unknown operator: %c\n", c); break; } } return 0; }

Questions about programming?Chat with your personal AI assistant