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;
}