I want to add zeroes at the starting of a string. I am using format specifier.
My input string is hello
I want output as 000hello
.
I know how to do this for integer.
int main()
{
int i=232;
char str[21];
sprintf(str,"%08d",i);
printf("%s",str);
return 0;
}
OUTPUT will be -- 00000232
If I do the same for string.
int main()
{
char i[]="hello";
char str[21];
sprintf(str,"%08s",i);
printf("%s",str);
return 0;
}
OUTPUT will be - hello (with 3 leading space)
Why it is giving space in case of string and zero in case of integer?
Use
"%0*d%s"
to prepend zeros."%0*d"
-->0
min width of zeros,*
derived width from the argument list,d
print anint
.An exception is needed when the string needs no zeros up front.
Yet I do not think
sprintf()
is the right tool for the job and would code as below.Output