Click here to Skip to main content
15,398,357 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to convert an int to a string but that has to be done in form of n digits.
i.e for 5 if user wants it in 5 digit space then 00005 , if in 6 digit space 000005.
I know that can be done in form of %05d etc but here the value is entered by the user so %0nd wont work . How can I do that.
sprintf(sol,"%nd",i);
How can this be corrected?
Thanks in advance

What I have tried:

The primitive thought was to use
%nd
but of course that didn't work.
Posted
Updated 9-Apr-17 19:48pm

1 solution

The magic incantation is "%*d" as a format specifier. You then provide another argument (integer) to specify the width. See any good reference on printf format specifiers.
(edit) you'll also need to specify leading zero padding. you'll find that in the sane reference.
   
v2
Comments
Peter_in_2780 10-Apr-17 2:24am
   
RTFM! Then try printf("%0*d", 5, 7);
CPallini 10-Apr-17 4:29am
   
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900