-
Infinite loop
I stumbled upon a problem while I was coding.
Code:
void main()
{
int n;
do
{
printf("Write a number in interval [10,100]\n");
scanf("%d",&n);
}while(n<10 || n>100);
}
This works just fine when I enter a number, but when I enter a char for example "A", it just starts repeating "Write a number in interval [10,100]\n" infinitely. I tried to explain this to myself but I just couldn't come to a logical conclusion.
In my opinion n should be initialized with 65 and program should leave the loop and end.
-
A isn't a number.
The next time around the loop, A still isn't a number.
The next time around the loop, A still isn't a number.
The next time around the loop, A still isn't a number.
Unless you do something to fix that, you're going nowhere.
Try using fgets() to read a whole line, then using say sscanf to parse it.
See the FAQ.
-
When you enter "A", scanf fails and n is not assigned any value. That is why the loop goes forever. Check the return value of scanf() to see if 'n' was successfully given a value.