2

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):

4

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

5 Comments

Ah, I see. Thank you for teaching me about this ^__^ C is tricky to learn, isn't it?
@REN you are welcome.. An image is a thousand words, so here is the answer: meme.
here is the finished application. pastebin.com/uzzrsUx3 If you have the time to spare please have a look at the code and play with the app ^__^
@REN the page cannot be displayed. Maybe my work network is blocking it, and it's lunch time.. To be honest, I am quite busy now, thanks though! Cheers
no worries, just want to let you know that I completed the program thanks to your help. Cheers ^__^

Your Answer

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