Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does scanf() check if the input is an integer or character?

Tags:

c

scanf

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?

like image 901
vjain27 Avatar asked Apr 12 '11 01:04

vjain27


2 Answers

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.

like image 141
poundifdef Avatar answered Sep 30 '22 22:09

poundifdef


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.

like image 41
BlueRaja - Danny Pflughoeft Avatar answered Sep 30 '22 22:09

BlueRaja - Danny Pflughoeft