-
While loop problem
Hi,
I have a small problem with part of a program I have made. I want the user to select a number between 1 and 25 so I have used the following code (which I have abridged):
<CODE>
printf("\nPlease enter the number of records you would like to add (up to 25):\n");
scanf("%d", &number);
while(number <1 || number>25)
{
printf("\nPlease re-enter the number of records you would like to add:");
scanf("%d", &number);
}
</CODE>
The only problem is when a character is entered it goes into an infinite loop displaying the "Please re-enter...." sentence. Is this because of scanf? Is there a better function to use.
Thanks in advance
-
First off, code tags are with these brackets: [ ]
Good try though :)
Now the scanf() question comes up a lot. The better way to do it is with fgets() then atoi(), but if you want to stick with scanf(), check it's return code.
You have asked it to get 1 number for you, so if it works, it will return 1. Check this in an if statement, if you don't get 1, ask the user to re-enter. Don't touch the number variable until scanf() returns 1.
-
Thanks Hammer!
Works a treat.:)