When my code checks if an input is an integer or string it goes into an infinite loop of outputting "invalid input" and "guess a number between 0-9" without giving the user a chance to input something new.
the code below is what I have
// Created on: Oct 2023
// This program allows the user to guess a number between 0-9
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
// this function allows the user to guess a number
// and the program decides if the user is correct
unsigned int seed = time(NULL);
int randomNumber = rand_r(&seed) % 9;
int num = 0;
int scanerrorcode = 0;
while (1)
{
printf("\nGuess a number between 0-9: ");
scanf("%d", &num);
if (num < 0 || num > 9) {
printf("\n%d is not between 0-9", num);
} else if (num == randomNumber) {
printf("\nYou guessed correctly!");
break;
} else if (num > randomNumber) {
printf("\nYou guessed too high!");
} else if (num < randomNumber) {
printf("\nYou guessed too low!");
} else {
printf("\nError, %d is not a number", num);
}
}
printf("\nDone.");
}
I am looking for a way to make this game using only a while loop and a break statement. The code should keep asking the user for an input until the random number is guessed
scanf()isn't satisfied when the mischievous user enters"foobar"so it leaves that in the input buffer only to find it again and again and again. Learn to usefgets()andstrtol()to both empty the buffer in one operation and to verify the user's input is what the program needs to work correctly. Move away fromscanf(). It's not for beginners...