I am learning C right now and im at the very beginning.
Here's my code:
#include <stdio.h>
int main (){
char operator;
double num1;
double num2;
double result;
printf("\n Enter an operator");
scanf("%c", &operator);
printf("Enter number 1:");
scanf("%lf", &num1);
printf("Enter number 2:");
scanf("%lf", &num2);
switch(operator){
break;
case '+':
result = num1 + num2;
printf("\nresult: %.0lf", result);
break;
case '-':
result = num1 - num2;
printf("\nresult: %.0lf", result);
break;
case '*':
result = num1 * num2;
printf("\nresult: %.0lf", result);
break;
case '/':
result = num1 / num2;
printf("\nresult: %lf", result);
break;
default:
printf("%c is not valid", operator);
}
return 0;
}
If I enter an operator other than / / * + or -, I get 'x is not valid' after entering the numbers, so I need your help with this. If I enter the wrong operator at the very beginning, how do I end the code right there so I don't have to enter that number?
I thought of using break func. or if-else but, I am not able to do that.
Thanks for your help!
I want the code to immediately display the 'wrong operator' error if I enter the wrong operator.
I thought of using break func. or if-else but, I am not able to do that.
Are you allowed to use any if statements? Or is it simply that you cant use an if-else to check if input operator equals each of valid operator separately?
If you can use one if statement you can use strchr(), which checks if a character (input) is found in a string (valid operators):
const char *valid_chars = "//*+-";
printf("\n Enter an operator");
scanf("%c", &operator);
if (!strchr(valid_chars, operator)) {
printf("Wrong operator");
}