I want to reimplement the GetInt() function from the CS50 library. I've mostly succeeded with the following code, but if I enter a single character, or CTRL+, I'm left with an extra newline so that I have to press Return before I'm prompted to enter a number. I'm using an empty while getchar() loop to consume erroneous input, and this is the single bug I've found in this method.
Here is the code, note that I have constrained the number to be between 1 and 10 because I'm using it for mario.c and I will change that later.
int getint(void)
{
int x;
char key[3] = {0, 0, 0};
char *ptr;
char c;
do
{
printf("Please enter a whole number between 1 and 10: ");
fgets(key, 3, stdin);
for (int i = 0; i < 2; i++)
{
if (key[i] != 0 && key[i] != 10)
{
if (!isdigit(key[i]))
{
key[0] = 0;
key[1] = 0;
key[2] = 0;
while ((c = getchar()) != 10 && c != EOF) {}
break;
}
}
}
x = strtol(key, &ptr, 10);
if (x > 10)
while ((c = getchar()) != 10 && c != EOF) {}
}
while (x < 1 || x > 10);
return x;
}
I realize there are other problems with this code in terms of portability, but I want to solve this newline issue first.