Hello all,

I have very recently started basic C-Programming and have decided to teach myself by trying to make a very basic calculator.

The only issue I'm having is with validating that the input is in the form (Number) (operator) (Number).

My operator validation works fine but if I type an invalid character for either of the numbers, I get an infinite loop of prinft("").

If anyone could try and see what the problem is I would be much obliged.

Thanks,

Sam.

Code:#include <stdio.h> #include <stdlib.h> int main(void) { /* Define variables and assign inital values for validation*/ int invalid_operator = 0, invalid_number = 0; char operator; float n1, n2, result, valid_input; /* Ask user for input and validate*/ printf("Please enter two numbers and your operation in the format:\n (Number 1) (operator) (Number2)\n"); if(3!=scanf("%f %c %f", &n1, &operator, &n2)) invalid_number = 1; /* If input is not valid, start while loop - ask user to input values until correct format is obtained*/ while(invalid_number == 1) { printf("One or more of your inputs are invalid. Please enter your two numbers along with a valid operator (+, -, * or /) in the format:\n (Number 1) (operator) (Number2)\n"); if(3!=scanf("%f %c %f", &n1, &operator, &n2)) invalid_number = 1; else invalid_number = 0; } /* Once input is validated, attempt to perform operation requested*/ if(operator == '+') result = n1 + n2; else if(operator == '-') result = n1 - n2; else if(operator == '*') result = n1 * n2; else if(operator == '/') result = n1 / n2; else invalid_operator = 1; /* If operator is not defined, start while loop - ask user to input values until valid operator is obtained*/ while(invalid_operator == 1) { printf("Your operator is invalid. Please enter your two numbers along with a valid operator (+, -, * or /) in the format:\n (Number 1) (operator) (Number2)\n"); scanf("%f %c %f", &n1, &operator, &n2); valid_input = (operator == '+') || (operator == '-') || (operator == '*') || (operator == '/'); if(!valid_input) invalid_operator = 1; else invalid_operator = 0; } if(operator == '+') result = n1 + n2; else if(operator == '-') result = n1 - n2; else if(operator == '*') result = n1 * n2; else if(operator == '/') result = n1 / n2; /* Print result*/ printf("The result of %f %c %f is: %f\n", n1, operator, n2, result); exit (EXIT_SUCCESS); }