what is the %2d in scanf

That's two digits number:

int n = 0;
scanf ("%2d", &n);
printf ("-> %d\n", n);

12 -> 12

88657 -> 88


The number right after the '%' sign and right before the type of data you wish to read represents the maximum size of that specific type of data.

As you are reading an integer (%2d), it will only allow an integer up to two digits long. If you were to read a 50 characters long array, you should use %49s (leaving one for the null terminating byte). It is the same idea.

int number = 0;
scanf("%2d", &number);
printf("%d", number);

If the user passed 21 for the scanf() function, the number 21 would be stored in the variable number. If the user passed something longer than 21, i.e. 987, only the first 2 digits would be stored - 98.

Tags:

C

Scanf