I am using what scanf() returns when it gets what is expects or when it doesn\'t. What happens is it gets stuck in the
while()` loop.
To my knowledge t
The problem here is, upon encountring an invalid input, (a character, for example), the incorrect input is not consumed, it remains in the input buffer.
So, in the next loop, the same invalid input is again read by scanf()
.
You need to clean up the buffer after identifying incorrect input. A very simple approach will be,
if (test == 0) {
printf("please enter a number");
while (getchar() != '\n'); // clear the input buffer off invalid input
testNum = 0;
}
That said, either initialize test
, or remove printf("%d", test);
, as test
being an automatic variable, unless initialized explicitly, contains indeterminate value. Attempt to use that can invoke undefined behavior.
That said, just to be nit-picky, return
is not a function, don't make it look like one. It's a staement, so return 0;
is much more soothing to the eyes and much less confusing, anyway.