# Need help with a calculator

• 02-24-2013
atac
Need help with a calculator
I'm writing an addition and subtraction calculator that takes input as: 5+6-3+2. You should be able to add or sub as many numbers as you want. I want the while loop to stop when the user hits enter. I put the getchar() function to catch the \n and break the loop but it is also swallowing the '-' sign, which I want to use to subtract and is instead adding the numbers with "sum+=number". How can I get around that?

Code:

```#include <stdio.h> int main(int argc, char *argv[]){     int number, sum = 0;     puts("Enter numbers to add or subtract: ");   while (scanf("%d", &number) == 1){         sum += number;         if(getchar() == '\n'){           break;         }        }   printf("Sum: %d\n", sum);     return 0; }```
• 02-24-2013
whiteflags
I think you should have scanf read in the operation and the number, not just the number. The first time you call scanf will be a special case if you do this though, because a math problem doesn't normally start with plus or minus, if you understand what I mean.

Also I think you should forget about the getchar() part altogether. If you stick to scanf, you don't really need it.
• 02-24-2013
Barney McGrew
Well, without knowing exactly what your program needs to do, you only make it harder for yourself to write. I suggest following the state table listed below.
 input effect nextstate state #1 EOF exit * newline none 1 number store the value 2 non-number eat the line, emit an error message 1 state #2 EOF exit * newline print the stored value 1 operator store the operation to be applied to the next number 3 non-operator eat the line, emit an error message 1 state #3 EOF exit * newline emit an error message 1 number apply the operation on the stored value and the number, and store the result 2 non-number eat the line, emit an error message 1
One of the challenges of programming is being able to take something like this and implement it with a programming language.
• 02-24-2013
Malcolm McLean
To do this type of parsing, life is a lot easier if you use the ungetc() function. To read something, pull out character using getchar() until you reach one that indicates end of that you are reading (eg a non-digit), then use ungetc() to put it back, to be read on the next pass.

scanf() can't distinguish between unary minus ( e.g. the temperature is -10) and the operator minus (3 - 2 == 1). So you need to read the minus, then if it's unary (doesn't follow an integer), negate the number. So 3 + --6 would give 9.

Pretty soon you'll want to extend your calculator to handle multiplies, divides, may sines and cosines and so on. Read my book on Basic interpreters (a Basic interpreter is basically a calculator with a few add-ons for flow control.