0

I am trying to make a calculator which firsts takes two numbers from the user then asks for the operation to be done and it then processes it produces the required output why this program is skipping 11th block scanf("%c" , &condition); I am using GCC compiler.

#include<stdio.h>
void main()
{
char condition;
double number_1 , number_2 , result;
printf("please enter first number : \n");
scanf("%lf" , &number_1);
printf("\n please enter secound number : \n");
scanf("%lf" , &number_2);
printf("\n please enter  +  , - , * , / \n ");
scanf("%c" , &condition);

switch (condition)
{
case '+':
    result = number_2 + number_1;
    break;
case '-':
    result = number_1 - number_2;
    break;
case '*':
    result = number_1 * number_2;
    break;
case '/':
    result = number_1 / number_2;
    break;
default:
    break;
}
printf(" \nyour result is %.1lf \n" , result);}
false
  • 10,264
  • 13
  • 101
  • 209
Krishanu dev
  • 45
  • 1
  • 7
  • 1
    Add space as in `" %c"`. This will "eat" the newline characters from the stream. – Eugene Sh. Dec 03 '20 at 16:22
  • Thank you so much can you please tell me what is the reason behind it? – Krishanu dev Dec 03 '20 at 16:33
  • When you input stuff, you usually hit "enter". This is translating to newline characters which remain in the stream. When you read a single character, this newline is read instead of what you would expect. So the rule for format strings is that the space will match any amount of whitespace characters (that is spaces, tabs or newlines) in the input. – Eugene Sh. Dec 03 '20 at 16:38
  • Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. – Weather Vane Dec 03 '20 at 16:49
  • Personally I am not a fan of the `" %c"` solution. I am of the opinion that every operation should clean up their own mess, rather than relying on the next operation to do the cleanup. That means if you do line-based input, you should do something equivalent to `while (fgetc(stdint) != '\n');` to eat rest of line right after each `scanf` (and its error checking) – HAL9000 Dec 03 '20 at 21:52
  • Thank everyone I love this community :) – Krishanu dev Dec 04 '20 at 13:07

1 Answers1

1

Space, tab, line feed (newline), carriage return, form feed, and vertical tab characters are called "white-space characters". All scanf() input format specifiers ignore white-space characters, except these: "%c", "%n", "%[]".

Since, you are using %c format specifier, scanf() reads that extra \n into the character variable c.

Solution : Use leading space. scanf(" %c" , &condition);

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26