Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the %2d in scanf

Tags:

c

scanf

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.

like image 918
Ashwin Avatar asked Dec 17 '12 09:12

Ashwin


2 Answers

That's two digits number:

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

12 -> 12

88657 -> 88

like image 194
user327843 Avatar answered Sep 20 '22 17:09

user327843


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.

like image 29
Roberto Fajardo Avatar answered Sep 19 '22 17:09

Roberto Fajardo