Language : C
Compiler : Visual Studio 2017 / Win 32
So basically i'm tasked with making a multiplication game that takes two random, single digit numbers and prompts the user to multiply them together. The program has to be bullet proof so it has to loop the user until they enter a correct input (If they enter a letter, for example, it must loop them until they enter the correct NUMBER). I've tried a couple things out, and the do/while loop seems to work pretty well. However, when the user enters an incorrect answer, and tries again, the scanf in the 2ND do/while loop will make them enter two inputs (ignores the first one). I've had this problem in the past and tried countless times to fix it but I cant find a solution. Any help would be really appreciated.
Thanks!
Tried using fgets. Failed miserably. I removed getchar() != '\n'. That worked, but then the program would loop "Please enter an integer" infinitely.
while (answer != correct)
{
srand(time(NULL));
int wrong = 1 + rand() % 5;
switch (wrong)
{
case 1:
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("\n ***\n");
printf(" Wrong!\n");
printf(" ***\n");
SetConsoleTextAttribute(h, wOldColorAttrs);
break;
case 2:
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("\n ***\n");
printf(" Nope!\n");
printf(" ***\n");
SetConsoleTextAttribute(h, wOldColorAttrs);
break;
case 3:
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("\n ***\n");
printf(" Not quite!\n");
printf(" ***\n");
SetConsoleTextAttribute(h, wOldColorAttrs);
break;
case 4:
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("\n ***\n");
printf(" Incorrect!\n");
printf(" ***\n");
SetConsoleTextAttribute(h, wOldColorAttrs);
break;
case 5:
SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("\n ***\n");
printf(" Nope! Try again!\n");
printf(" ***\n");
SetConsoleTextAttribute(h, wOldColorAttrs);
break;
}
do {
printf("Enter a number to represent your answer! ");
while (getchar() != '\n');
} while (scanf_s("%d", &answer) != 1);
getchar();
}
I just want the user to be able to smoothly enter a number without the confusing scanf bug.