Tutorial :My program is not asking for the operator the second time



Question:

#include<stdio.h>  #include<stdlib.h>       main(){      int b,c,r,d;      char a;         while(1){         printf("Enter the operator\n");              scanf("%c",&a);              if(a=='+') d=1;            if(a=='-') d=2;            if(a=='&') d=3;             if(a=='|') d=4;            if(a=='.') d=5;              printf("Enter the operands\n");              scanf("%d",&b);               scanf("%d",&c);              switch(d){              case 1:r=c+b;              break;              case 2:r=c-b;                 break;              case 3:r=c&b;              break;              case 4:r=c|b;              break;              case 5:exit(0);              deafult:printf("Enter a valid operator");          }          printf("Result = %d\n",r);      }  }  

Output:

Enter the operator  +  Enter the operands  8  7  Result = 15  Enter the operator  Enter the operands  


Solution:1

scanf("%d",... will read a number (skipping whitespace beforehand) but leave the newline on the input stream. scanf("%c",... will read the first character, and does not skip whitespace.

One simple modification is to use

scanf(" %c", &a);  

This will tell scanf to skip any whitespace before the character.


Solution:2

That because of the function scanf width param "%c", after the 1st time loop, at line scanf("%d",&c);, like +, there's a end-line character in the input stream, then the second loop, scanf get the end-line character as the input and parse it to a; To fix this, you can add a scanf("%c"); line right after scanf("%d",&c);


Solution:3

have a look at scanf error in c while reading a character


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »