I have a section of code where I check the input to scanf is valid. i.e. if scanf returns a non zero positive number. This is part of my code:
while(scanf(" %d",&choice)<=0){
printf("Incorrect value entered, please re-enter\n");
}
Where “choice” is an integer.
Every time I run this code, the compiler skips past the scanf after the while loops is executed. I get an output like this:
Welcome to the Predator/Prey Calculator
Please enter your name
Dan Hi Dan
Please choose one of the following options: 1. Calculate the evolution of a TYPICAL predator and prey system 2. Calculate the evolution of a SPECIFIC predator and prey system 3. Calculate the evolution of a CUSTOM predator and prey system 0. Quit a Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter Incorrect value entered, please re-enter
Incorrect value entered, please re-enter
Could you explain why this happens! I can’t seem to find any answers on the internet specific to reading in integers.
Many thanks,
> 0
? Like 1,15,100 ? – Michiscanf()
returns the number of fields successfully converted: please read the man page. – Weather Vane