cscanf

How does scanf recognize the input(string) as integer?


I'm wondering how scanf in C recognizess the input,which is a string, as intger when the conversion specifier is %d For example,

#include <stdio.h>
int main()
{
    int x;
    scanf("%d",&x);
    printf("%d \n",x);
}

When my input is 123456, how does scanf interpret this string as an integer? Also, what's the difference between recognizing the input string when the conversion specifiers in scanf are %hd and %d?


Solution

  • scanf() scans the format string and reads bytes from stdin to try and match expected sequences specified in the format string. A format of %d commands scanf() to read bytes and compute the value of an int from the decimal representation. For this, it follows these steps:

    If no digits have been seen, stop the scanning process and return the number of formats correctly stored so far, which may be 0 if %d is the first conversion format or EOF if no conversions have been performed and the end of file has been reached or a read error occurred.

    If at least one digit was seen, apply the optional negative sign to the computed value then store the result to the pointer passed as an extra argument to scanf(). If the format was %hd, this pointer is a short *, so the value will be converted into a short before storing.

    Continue scanning the format string until its end.