0

I have a program that is meant to continue looping as long as an entered character is 'y', but my code exits after one execution of the do-while loop.

int main()
{
    char cont;

    do {
        printf("Would you like to continue (y/n)?: ");
        scanf_s("%c", &cont, sizeof(cont));
    } while (cont == 'y');
}

This will take in one key press and either exit or continue, as it's supposed to, but then immediately exit without waiting for more key presses.

1
  • This is a good example of why taking user-input with scanf is discouraged. When reading a line of input use a line-oriented input function like fgets() or POSIX getline(), Then it's char buf[128]; do printf("continue (y/n)?: "); if (!fgets (buf, sizeof buf, stdin)) { puts ("(user canceled input)"); return 1; }; } while (*buf == 'y'); Commented May 6, 2020 at 5:07

1 Answer 1

1

It seems the newline character after "y" is read in the 2nd loop, and the loop is exited because the newline character is not y.

You should add a space character to have it skip whitespace characters like this:

scanf_s(" %c", &cont, (unsigned)sizeof(cont));

Also note that the size parameter for scanf_s is type unsigned, not size_t.

scanf_s, _scanf_s_l, wscanf_s, _wscanf_s_l | Microsoft Docs

Related: c - What does space in scanf mean? - Stack Overflow

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.