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.

Cownerrr
  • 31
  • 3
  • 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');` – David C. Rankin May 06 '20 at 05:07

1 Answers1

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

MikeCAT
  • 73,922
  • 11
  • 45
  • 70