I know the meaning of this statement
scanf("%d",&x);
But what does this statement do
scanf("%2d",&x);
I tried searching for this, but could not find an answer. I want to know what happens internally also.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With