Home > OS >  How to repeat character input if the user enters the wrong one?
How to repeat character input if the user enters the wrong one?

Time:12-12

I tried this code but it's not working and I honestly don't know what is wrong here. I think that this logic would work with numbers, but that appears not to be the case with characters.

Edit: I just realised my mistake and corrected it in an answer.

char choice;

printf("\nAre you ready? (y/n) ");
    scanf(" %c", &choice);

    while (choice != 'y' || choice != 'n') {
        printf("\n\nYou can only answer with y or n!");
        scanf(" %c", &choice);
    }

    if(choice == 'n') {
        printf("\nYour answer was no.");
    }

    else if(choice == 'y') {
        printf("\nYour answer was yes.");
    }

CodePudding user response:

My bad, the logic is good, I just wrote OR || instead of AND && in while loop.

It should be like this:

while(choice != 'y' && choice != 'n')

CodePudding user response:

First of all, as already said in comments, (chice != 'y' || choice != 'n') will always be true. Logically, you should use && instead of || there.

Moreover, in C when you take any input, you have an additional \n character added to the input byffer. Therefore, when your while loop runs for the first time, it doesn't read a new character, but instead it reads the \n from the previous input. A way to fix that is to call getchar() after each scanf call.

  •  Tags:  
  • c
  • Related