lucas lucas - 23 days ago 8
C Question

For if statement, although it is true, it loops again

#include <stdio.h>

void clearKeyboard(void){

while(getchar()!='\n');
}

void pause(void){

printf("Press <ENTER> to continue...");
clearKeyboard();
}


int getMenuChoice(void){

int choice;
printf("1- List all items\n");
printf("2- Search by SKU\n");
printf("0- Exit program\n> ");

scanf("%d", &choice);

return choice;
}

int getYesOrNo(void){

char ch;
int ret;
ch = 0;
ret = 0;

while(ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n')
{
scanf("%c", &ch);
clearKeyboard();
if (ch == 'Y' || ch == 'y'){
ret = 1;
return ret;
}
if (ch == 'N' || ch == 'n'){
ret = 0;
return ret;
}
else if (ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n'){
printf("Only (Y)es or (N)o are acceptable: ");
}
}
return ret;
}

int main(void){

int choice;
int temp = 0;
choice = 0;

printf("=== TEST MENU ===\n");
pause();
while(temp == 0){
choice = getMenuChoice();
if (choice != 0){
printf("*** not implemented ***\n");
}
else{
printf("Do you really want to quit? ");
temp = getYesOrNo();
}
}
printf("=== END OF MENU TEST ===\n");

return 0;

}


When the code runs, it should print out the test menu
and I would have to press enter to continue

Then, it would display multiples of print statements(listall..search by...exit)

So, if the user types 0 in, it asks Do you really want to quit and if the user types y, it should quit

However, the problem is the program asks the user unnecessary question "Only (Y)es or (N)o are acceptable" one more time after it asks "Do you really want to quit?" when I already have typed y in which is valid answer.

Why is that?

p.s library is there existing

Answer

Scanf ("%d", &choice); consumes only the numeral character ( also crashes on any other input, iirc) but not the \r \l or \n characters, which will be consumed during the getYesOrNo function, if I am correct (somebody please correct me). That's why the program should display the (y)es/(n)o reminder directly after asking you whether you'd really want to quit.

That is also the reason why adding the clearKeyboard function makes it work as intended.

Comments