user11008708
user11008708

Reputation:

Having trouble with do...while loop

So basically I'm trying to create a simple buffer for input.

If the user inputs something other than the letter 'R' or 'S', then the do while loop will return the code back to where the user inputs the letter.

However, when I tried entering 'Z' for example, the loop repeats itself twice, asking for input on the second loop.

I don't understand why, please help me understand.

I tried... using a while loop? That doesn't work. I don't want to use goto.

<stdio.h>
<stdlib.h>

int main(void)
{
    char r_or_s;

    printf("Number Reverser/Shuffler v0.1\t");
    printf("Written by REN\n");
    printf("This program reverses and shuffles the order of numbers.\n\n");

    do
    {

        printf("Would you like to reverse or shuffle numbers? (Press R/S):");
        r_or_s = getchar();
        printf("\n");

        if (r_or_s == 'R')
        {
            reverseno();
        }

        else if (r_or_s == 'S')
        {
            shuffleno();
        }
    } while (r_or_s != 'R' || r_or_s != 'S');

    return 0;
}

Expected output of

Would you like to reverse or shuffle numbers? (Press R/S):

after rejection of input, but the actual output is:

Would you like to reverse or shuffle numbers? (Press R/S): Would you like to reverse or shuffle numbers? (Press R/S):

Upvotes: 2

Views: 85

Answers (1)

gsamaras
gsamaras

Reputation: 73366

This happens because you input 'Z' for example, then you also pressed the Enter!

So, how many characters did you input? Two!

Then getchar() consumes 'Z' from the standard input buffer, goes back to read again from user, but the newline character (Enter) awaits in the Standard input buffer.

As a result, getchar() consumes the newline character now, resulting in "the loop repeating itself twice".

You have to take into account the newlines as well. For instance, you could do this:

if(r_or_s == '\n')
    r_or_s = getchar(); // we read the trailing newline character before, read again

Moreover, you want to stop looping when the user input 'R' or 'S, thus you need to change this:

while (r_or_s != 'R' || r_or_s != 'S');

to this:

while (r_or_s != 'R' && r_or_s != 'S');

Upvotes: 1

Related Questions