Let's look at your code.
int main()
{
int someInt = 01;
char str[12];
sprintf(str, "%d", someInt);
printf("%d",strlen(str));
}
As noted in the comments, 01
is an integer literal and you've written... 1
. Let's also initialize every character in your string to '\0'
to avoid potential null terminator issues, and print a nice newline at the end of the program.
int main()
{
int someInt = 01;
char str[12] = {0};
sprintf(str, "%d", someInt);
printf("%d\n", strlen(str));
}
It still prints 1
, because that's how long the string is, unless we use modifiers on the %d
specifier. Let's give that field a width of 2
with %2d
.
As suggested, in comments on this answer, the correct format specifier for printing the length of a string is %zu
as the result of strlen
is of type size_t
rather than int
.
int main()
{
int someInt = 01;
char str[12] = {0};
sprintf(str, "%2d", someInt);
printf("%zu\n", strlen(str));
}
Now it prints 2
.
If you want to store "01"
in str
, you could modify it to print leading zeroes to pad the int with %02d
.