How can I modify my code so that ,when the input is not a integer, display \"Inv
ID: 3721862 • Letter: H
Question
How can I modify my code so that ,when the input is not a integer, display "Invalid input, try again", and when the input is not in the range of 1~100, display "Guess out of bounds, try again"
. A function that prompts the player for a guess. This function should keep prompting the player until a valid integer, within the allowed bounds (1 to 100), is entered. The function should then return the guess. If the player supplies an invalid input (e. g. a character, or a floating-point number, scanf O will fail to return 1 (which would mean that it was able to read one integer number). In this case, we need to manually empty the inpuit buffer In order to empty the input buffer, you can use the following code: Bats the bad input until the newline character while (getcharIn') This loop keeps reading characters one by one until a newline character is found.Explanation / Answer
Given below is the modified code for the question.
Please do rate the answer if it was helpful. Thank you
int prompt(void){
int guess;
while(1)
{
printf("What is your guess? ");
if(scanf("%d", &guess) == 1) //got an int input
{
if(guess < 1 || guess > 100) //out of bounds?
printf("Guess out of bounds, try again. ");
else
break; //valid input
}
else
{
printf("Invalid input, try again! ");
//flush everything till newline
while(getchar() != ' ')
;
}
}
return guess;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.