1

I am trying to run this simple calculator code, and i don't know what's the problem with running this code.

After i enter the two operands (Num1 & Num2), the program automatically jumps to the switch default message, i have trying to check same codes over the internet and they look exactly the same...

Can someone please point what am i doing wrong ? (Running on visual studio 2017) Thanks !

  int main() {
double Num1, Num2;
char operator;

printf("Enter first number:\n");
scanf("%lf", &Num1);

printf("Enter second number:\n");
scanf("%lf", &Num2);

printf("Enter operator: + or - ");
scanf("%c", &operator);

switch(operator)
{

case '+':
    printf("%.1lf + %.1lf = %.1lf", Num1, Num2, Num1 + Num2);
    break;

case '-':
    printf("%.1lf - %.1lf = %.1lf", Num1, Num2, Num1 - Num2);
    break;

default:
    printf("Operator is not correct");


}

return 0;

}

Blaze
  • 16,736
  • 2
  • 25
  • 44
Yuvi1
  • 9
  • 7

1 Answers1

2

The problem is that scanf leaves the newline in the buffer. This is no problem for your float reads, but the char read will fail because the newline is taken as a char and that doesn't match in your switch. You can fix it by changing your read to this:

scanf(" %c", &operator);

Note the space in " %c". With this you're telling it to discard the leading whitespace (which in this case is the newline).

The documentation offers following explanation:

whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling isspace in a loop). Note that there is no difference between "\n", " ", "\t\t", or other whitespace in the format string

.

Blaze
  • 16,736
  • 2
  • 25
  • 44