简体   繁体   中英

Do-while loop using C

I'm using a while loop per below:

do {

    scanf("%c", &turnChoice);

    if (turnChoice == 'r')
    {
        invalidSelection = false;
    }

    else if (turnChoice == 'h')
    {
        invalidSelection = false;
    }

    else
    {
        printf("Invalid input.\n");
    }

} while (invalidSelection == true);

However, before stopping for the user input, it runs the full loop once (so it displays "Invalid input" and then asks the user for a letter). What am I doing wrong?

My guess is that you have some input before the code you show, some input that you end with a newline, right?

The problem here is that the newline is still in the input-buffer when you call scanf to read a character, so that newline is what you read and get.

There is a very simple "trick" to tell scanf to read and discard leading white-space (like newlines), and that is to prepend a single space to the format string, so try eg

scanf(" %c", &turnChoice);
//     ^
//     |
// Note space here

After take char input, we need to take '\\n' char which is giver by pressing the enter button

    char turnChoice;
    bool invalidSelection = true;
    do {

    scanf("%c", &turnChoice);// if you want to give leading space then use scanf(" %c",&turnChoice);
    getchar();
    if (turnChoice == 'r')
    {
        invalidSelection = false;
    }

    else if (turnChoice == 'h')
    {
        invalidSelection = false;
    }

    else
    {
        printf("Invalid input.\n");
    }

} while (invalidSelection == true);

This might help, when you scanf put "%*c" after your first character to ignore the enter key that you hit after entering the input. Code is as follows:

do {

scanf("%c%*c", &turnChoice);

if (turnChoice == 'r')
{
    invalidSelection = false;
}

else if (turnChoice == 'h')
{
    invalidSelection = false;
}

else
{
    printf("Invalid input.\n");
}

} while (invalidSelection == true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM