tags:

views:

94

answers:

3
#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
+2  A: 

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);

Bang Dao
why don't the subsequent scanf operations (to get operands) read that newline?
sje397
There're many ways to solve this kind of problems, so I think the reason is more important. By knowing that, we can come up with many solutions. Here is just a easiest way to fix this code without editing current code, in my opinion.
Bang Dao
But that is not quite the reason. The newline is not left over from the first `scanf("%c"...`, but from the last `scanf("%d"...`.
sje397
Bang Dao
+2  A: 

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.

sje397