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?
I am wondering how does the standard C library function scanf() check if the
Share
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, thestrtol()function does the looping to perform that conversion.