Reputation:
My Code:
#include<stdio.h>
char checkInput0(void);
int main() {
char output;
output = checkInput0();
printf("The output is %c", output);
}
char checkInput0(void){
char option0 = '\0',check0;
char c;
do{
printf("Please enter your choice: ");
if(scanf("%c %c",option0, &c) != 'A' || c != 'B' ){
while((check0 = getchar()) != 0 && check0 != '\n' && check0 != EOF);
printf("[ERR] Please enter A or B.\n");
}else{
break;
}
}while(1);
return option0;
}
I would like to only allow the user to input only "A" or "B" and if anything else would be entered I would like to reprompt the user with the following message: [ERR] Please enter A or B.\n
I have written a funktion which worked with numbers but I can't get the one above (checkInput0) to work, what have I done wrong
Upvotes: 0
Views: 1090
Reputation: 234635
scanf
does not return c
, it returns the number of variables successfully set. Comparing that to 'A'
is pretty pointless.
Change your scanf
call to scanf("%c %c", &option0, &c)
: currently the behaviour is undefined: the variable arguments need to be pointer types.
x != 'A' || x != 'B'
is 1
for any value of x
.
Consider moving scanf
outside the if
conditional: checking the return value of scanf
explicitly. On the third point, did you want &&
?
Also be careful with ace code that writes c
on one side of an operator, and reads it on the other. It's fine in this instance since ||
is a sequencing point, but you are quite close to undefined behaviour here.
Upvotes: 2