0

I have this code, a program to take an integer from a user that's negative, if not trap them in a loop until they enter a negative integer. I have this part down, however, how could i clear the input buffer?

I tried to use while ((getchar()) != ‘\n’); after the first scanf_s but it fails.

here is code

#include <stdio.h>

int main()

{
int num;

printf("Please enter a negative integer");
scanf_s("%d", &num);

while (num >= 0.0)
{
    printf("Please enter a negative integer!\n");
    scanf_s("%d", &num);
}

    printf("%d", num);


system("pause.exe");
return 0;
}
3
  • Check return value of scanf_s. Commented Oct 16, 2017 at 3:06
  • 2
    A simple search turns up many duplicates.... Commented Oct 16, 2017 at 3:07
  • 1
    Note that an indefinite loop is not sensible or user friendly. If the user hasn't managed to get it right in 10 attempts, it is unlikely that attempts 11..9999 are going to much more successful. Commented Oct 16, 2017 at 3:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.