开发者

My program is not asking for the operator the second time

开发者 https://www.devze.com 2023-01-10 14:32 出处:网络
#include<stdio.h> #include<stdlib.h> main(){ int b,c,r,d; char a; while(1){ printf(\"Enter the operator\\n\");
#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


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号