0

edit1: Sorry, I am in an intro to programming class... I read the two links, but don't fully understand them...

I tried to to add

    if (scanf_s("%d", &input) == 0) {
        fflush(stdin);
        continue;
    }

but that didn't seem to do anything. I understand that scanf is in an error state, so it will refuse to run, and that I need to clear a buffer of the bad input from user.

so basically, I am looking for a beginner's solution, for someone who just learned about loops, input/output, and basic error check.

~~~~~~~~~

I am new to C and have a small question. I want to read a list of integers from the console. It works fine if the user does indeed input integers, but if it types something like "acdb", or "0.5", I just get the program printing "enter a number: " infinitely, as if it's running the loop but scanf_s is broken and so it just skips itself.

Thanks for your help.

int input = 1;  
while (input != 0) {
        printf("enter a number: \n");
        scanf_s("%d", &input);

/* rest of code omitted */

}
sksumii13
  • 1
  • 1

1 Answers1

1

scanf_s returns the number of variables in the variable argument list that were successfully filled with data.

In your case you want that to be 1 therefore.

If you do encounter invalid input then it's your job to clear that, otherwise it remains on the input stream. For more on that see How to clear input buffer in C?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • The problem is that if someone enters 2.5 scanf_s still returns 1, and the stdin still contains .5. The solution in the duplicate question also doesn't account for this. Both questions say they want only integers to be input into the console but neither solution checks for only integers. – Zebrafish Mar 04 '18 at 21:16