-
infinite loop
Hi:
Could someone please help?
I want to check if input valid or not. But my code doesn't stop as expected.
Code:
void validateSex(char sex) {
if ( sex != 'M' || sex != 'F') {
printf("Input Error: Invalid \n");
do {
printf("Enter your sex (M or F): ");
scanf("%c", &sex);
}while (sex !='M' || sex!='F');
}; /* End if */
}
whats wrong with it?
Thanks
-
> while (sex !='M' || sex!='F')
sex = M, so sex != 'F' is true, so round the loop you go.
sex = F, so sex != 'M' is true, so round the loop you go.
Perhaps && instead.
-
> if ( sex != 'M' || sex != 'F') {
That's always true.
-
Your current implementation is using an unnecessary do loop and if statement. If you are going to evaluate if it is true or false before the do loop anyways, there is no reason to even use it. Just use a while loop instead.
Code:
void validateSex(char sex) {
while (sex !='M' && sex !='F') {
printf("Enter your sex (M or F): ");
scanf("%c", &sex);
}
}
-
Thanks for your help.
Problem solved.