Search code examples
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:

    • first read and discard any bytes that match isspace(): ' ', '\t', '\r', '\n', '\v', '\f' and possibly some other values.
    • then read an optional sign: - or +. Set the initial value to 0.
    • then repeatedly read bytes that correspond to digits: 0 to 9. Compute the value represented by these digits: for each digit, multiply the value computed so far and add the value of the digit, (c - '0') for all character sets.
    • stop whenever the byte read is not a digit, and push this byte back into stdin with ungetc(c, stdin);

    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.