-1

I want to write a simple calculator in C but when I run this code it just gets my numbers and doesn't get my operator and goes out from the running window! and when I move my scanf operator to top of the other scanf, it works right! why?!!!!

float num1, num2;

char op;
scanf("%f", &num1);
scanf("%f", &num2);
scanf("%c", &op);

switch(op)
{
    case '+':
    printf("%f + %f = %f", num1, num2, num1 + num2);
    break;
    case '-':
    printf("%f - %f = %f", num1, num2, num1 - num2);
    break;
    case '*':
    printf("%f * %f = %f", num1, num2, num1 * num2);
    break;
    case '/':
    printf("%f / %f = %f", num1, num2, num1 / num2);
    break;

    default :
    printf("error");
}

return 0;
ermia.l
  • 1
  • 3

1 Answers1

2

The format string in this call

scanf("%c", &op);

is used to read all characters including white space characters from the input buffer. So after you entered the last number this call read the new line character '\n'.

Instead use

scanf(" %c", &op);
      ^^^

This allows to skip white space characters in the input buffer.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks for your answer but if it takes white space as my operator so why it didn't run default ?! – ermia.l Dec 22 '19 at 15:47
  • @ermia.l I have not understood what you mean/ The space in the beginning of the format string allows to skip for example the new line character '\n' that appears the input buffer when you press the Enter key. – Vlad from Moscow Dec 22 '19 at 21:26