I am wondering how does the standard C library function scanf() check if the input is an integer or a character when we call scanf("%d",&var) when a character itself is just a number? I know that when it encounters a non-integer it puts it back into the input buffer and returns a -1 but how does it know that the input is not an integer?
You're correct in that each character is really represented as an 8-bit integer. The solution is simple: look at that number, and see if it is in the range 48-57, which is the range of SCII codes for the characters '0' - '9'.
Starting on line 1315 of the scanf()
source code we can see this in action. scanf()
is actually more complicated, though - it also looks at multi-byte characters to determine the numeric value. Line 1740 is where the magic happens and that character is actually converted into a number. Finally, and possibly this is the most useful, the strtol()
function does the looping to perform that conversion.
The input is always a string. If scanf
is expecting an integer (because you passed it "%d"
), it attempts to convert the string to an integer for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With