The function scanf
will try to read a decimal integer from stdin
. It uses the definition of a decimal integer from strtol
:
The valid integer value consists of the following parts:
- (optional) plus or minus sign
- (optional) prefix (0) indicating octal base (applies only when the base is 8 or 0)
- (optional) prefix (0x or 0X) indicating hexadecimal base (applies only when the base is 16 or 0)
- a sequence of digits
In other words, scanf
will try to interpret a sequence of characters on stdin
as a decimal integer. It will not do a character to integer conversion based on the ASCII table.
The solution to your problem lies in checking the return value of scanf
, which is:
Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.
So, check if scanf
did not return 1. In this case, it has not read a decimal integer and num
has not been assigned a value and should not be used.
In the given program, if num
has never been assigned a value, its value is indeterminate. This could be a value <40, explaining the infinite loop as scanf
repeatedly tries to read a non-integer from stdin
, fails and leaves the non-integer on stdin
as is. If num
has been assigned a value before, it will still hold that value after a failed scanf
call.