Error in scanf_s and switch-case statements

Asked 1 years ago, Updated 1 years ago, 371 views

#include <stdio.h>

int main(void)
{
   int num1, num2;
   char arithmetic;

   printf ("Please enter 2 numbers and an operator."\n\n");

   printf ("Operators are as follows:\n");
   printf("plus:+, subtract:-, multiply:*, divide:/\n");
   printf ("Input Order: Integer 1 Operator Integer 2\n\n");
   scanf_s("%d %c %d", &num1, &arithmetic, &num2, sizeof(num1), sizeof(arithmetic), sizeof(num2));

   switch(arithmetic)
   {
    case'+':
      printf("%d %c %d = %d\n", num1, arithmetic, num2, num1 +num2);
      break;
    case'-':
      printf("%d %c %d = %d\n", num1, arithmetic, num2, num1 -num2);
      break;
    case'*':
      printf("%d %c %d = %d\n", num1, arithmetic, num2, num1 *num2);
      break;
    case'/':
      printf("%d %c %d = %d\n", num1, arithmetic, num2, (float)num1 /num2);
      break;

   default:
      printf("Invalid operator entered.\n");
      break;
   }

   return 0;
}

I made it with but I can't print out the switch-case statement in the back... What's the problem?

c++

2023-01-01 13:48

1 Answers

Wrong place 1

scanf_s("%d %c %d", &num1, &arithmetic, &num2, sizeof(num1), sizeof(arithmetic), sizeof(num2));

It should be done as below.

scanf_s("%d %c %d", &num1, &arithmetic, sizeof(arithmetic), &num2);

Wrong place 2

printf("%d %c %d = %d\n", num1, arithmetic, num2, (float)num1 / num2);

It should be done as below.

printf("%d %c %d = %f\n", num1, arithmetic, num2, (float)num1 / num2);


2023-01-01 16:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.