Whatzat
Whatzat

Reputation: 81

Program issue on OS X but not on Windows in C

I am doing a small calculator program on XCode in C (on a macbook so). I give you the code here :

#include<stdio.h>


int readOpnd(){
   int opnd;
   printf("\nInput Operand > ");
   scanf("%d", &opnd);
   fflush(stdin);
   return opnd;
}


char readOp2(){
   char op;
   printf("\nInput Operator > ");
   scanf("%c", &op);
   if (op != '+' && op != '-' && op != '*' && op != '/'){
      fflush(stdin);
      return readOp2();
   }
   fflush(stdin);
   return op;
}

char readOp(){
   char op;
   printf("\nInput Operator > ");
   scanf("%c", &op);
   while (op != '+' && op != '-' && op != '*' && op != '/'){
      printf("\nIncorrect operator, try again >");
      scanf("%c", &op);
      fflush(stdin);
   }
   fflush(stdin);
   return op;
}


int apply(char op, int opnd1, int opnd2 ){

   if (op == '+')
      return opnd1+opnd2;
   if (op == '-')
      return opnd1 - opnd2;
   if (op == '*')
      return opnd1*opnd2;
   if (op == '/')
      return opnd1/opnd2;
   else{
      printf("invalid use of apply function");
      exit(1);
   }
}

int main(){
    char op;
    int result, opnd1, opnd2;

    while(1){
       opnd1 =  readOpnd();
       opnd2 = readOpnd();
       op = readOp();
       result = apply(op, opnd1, opnd2);
       printf("\nresult = %d", result);
       while(1){
          opnd2 = readOpnd();
          op = readOp();
          result = apply(op, result, opnd2);
          printf("\nresult = %d", result);
       }
    }   
    exit(0);
}

However When I execute it I have a problem. I put the first operand and then the second operand and then I have automatically the message "Incorrect operator, try again" without input an operator. For example :
Input Operand > 6

Input Operand > 4

Input Operator >

Incorrect Operator, try again >

The weirdest is that I don't have this problem on a Windows computer, I have not the "Incorrect Operator, try agin" message and the code works perfectly. I have also tried to run it on my mac console but I have the same problem.

Have you got a solution to this problem please ?

Thanks in advance

Upvotes: 0

Views: 103

Answers (1)

ryanpattison
ryanpattison

Reputation: 6251

The scanf for the operator character is reading '\n' from the last input.

do {
   scanf("%c", &op);
} while (op == '\n');

You cannot flush stdin the way your trying, see here.

Upvotes: 1

Related Questions