1

The user has only two choices 'a' or 'b', if the users input is not 'a' or 'b' an error message should prompt them to enter only 'a' or 'b'.

THE GOOD: I enter the letter 'a' and it bypasses the while loop.

THE BAD: when I enter 'b' it doesn't bypass the while loop?

Any suggestions on fixing this?

#include <stdio.h>
int main(void)
{
    char c;

    printf("enter a or b to make it out!\n");

    //loop if answer is NOT a or b
    while ((c = getchar() != 'a') && (c = getchar() != 'b'))
    {
        //let the user know there has been a problem!
        printf("That value is invalid");
        printf("\nPlease enter a or b:\n");
        fseek(stdin,0,SEEK_END);
    }

    printf("You made it out!");
    return 0;
}
1
  • You read two characters because you call getchar twice. You end up grabbing the newline character \n too. So when you type a, c = getchar() != 'a' evaluates to false and it skips the loop (I think skipping the second condition as well due to short circuiting). But when you type b, 'b' != 'a' and '\n' != 'b', so it enters the while loop. Also, I'm pretty sure this is executed as c = (getchar() != 'a'), which is presumably not what you're expecting. Nov 20, 2016 at 22:16

2 Answers 2

1

Whenever you do a getchar() a _different_ character is read. So you should change the while loop as

while (((c = getchar()) != 'a') && (c != 'b'))

Otherwise whenever the condition c = getchar() != 'b' is checked, c will be \n.

What is more, you should get that \n out of the way. So you may add another getchar() in your while loop whose return value you do not need to use.

0
1

Multiple problems:

  • c = getchar() != 'a' does not store the character read into c, it reads and discards the character and stores the result of the comparison into c.

  • You should test the value of the character read instead of reading a second character.

  • You should also check for end if file, and use an int to allow for all values of unsigned char and the special value EOF.

  • rewinding stdin to read further bytes will not produce what you expect: either it succeeds and you will reread the same bytes or it may fail is stdin is unbuffered and tied to a device.

Try this:

#include <stdio.h>

int main(void) {
    int c;

    printf("enter a or b to make it out!\n");

    //loop if answer is NOT a or b
    while ((c = getchar()) != EOF && c != 'a' && c != 'b') {
        //let the user know there has been a problem!
        printf("That value is invalid");
        printf("\nPlease enter a or b:\n");
    }
    printf("You made it out!\n");
    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.