0

I'm still learning the basics of C right now and I wanted to build a simple 'enter y to loop the program' that I've seen in a lot of console programs and wrote the following code to test it out. When I do execute it however, it does work as intended once after which the program just exits. It would help me a lot if anyone told me what I'm doing wrong here :

int main()
{
char l;
    do
    {
        printf("Loop successful.\n");
        fflush(stdin);  //I heard this has to be used because scanf keeps the enter key in buffer or something like that
        scanf_s("%c", &l);
    } while (l == 'y');
}

I also get a "Missing integer argument to 'scanf(_s)' that corresponds to conversion specifier '2'" warning and I don't seem to understand what I'm being warned against.

Chronos
  • 33
  • 5
  • A little advice; naming a variable `l` is (a) uninformative, and (b) can be mistaken for a `1`, depending on font; I had to do a double-take on `while (1 == 'y')`... – Ken Y-N Oct 16 '20 at 05:12

1 Answers1

2
fflush(stdin);  //I heard this has to be used because scanf keeps the enter key in 

That's wrong, fflushing stdin is undefined behaviour, what you need to do is consume the newlines lefted by the previous scan, just switch from

    scanf_s("%c", &l);

to

    scanf_s(" %c", &l); // Notice the space before %
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 2
    (.... with the note that there is one non-conforming OS that does define `fflush(stdin)` contrary to what is stated in the C-standard.. Cough... Microsoft...) – David C. Rankin Oct 16 '20 at 05:07
  • This does fix the issue, but how does adding a space fix this? I never put a space when I was working with %d for example. – Chronos Oct 16 '20 at 05:07
  • 1
    Because `"%c"` and `"%[...]"` do NOT ignore leading whitespace. So adding a whitespace to the format string tells `scanf()` to ignore all whitespace in that position. `'\n'` is whitespace... (which is also why new C programmers are urged to use `fgets()` for all user input and the use `sscanf()` to parse values from the input...) – David C. Rankin Oct 16 '20 at 05:09