Question : leading zeros on int

Hi,
My memory on C is a little flakey.

Something quite simple yet having some issues with it.
I have an int
i = 006;
and a string
 myString = Sam;

I would like to increment i
i++;
and then join it to sam

myString += i;

however its giving me Sam7 instaed of Sam007

How can i do this effectivley without losing my leading 0's.
Cheers.

Answer : leading zeros on int

I see you posted this in both the C# and C zones.

So far, the replies have been about C#, but the first line of your question suggests that you're using C. So I'll assume this question is about C and not C#.

You can use sprintf to construct a string like this. For example, see the below code sample.

Note that an int does NOT contain leading zero's - it simply contains the integer value. Adding leading zero's is a formatting issue, and you'll have to take care of that when you output the int value somehow. In the code snippet below, it's done using %03d, which means that an int (d) should be shown, that it should take up minimum three positions (3), and that it should be pre-pended with zero's if needed (0). Refer to the reference page for sprintf for more information :

        http://cplusplus.com/reference/clibrary/cstdio/sprintf/
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
#include <stdio.h>

int i = 6;                                /* the initial values */
const char* myString = "Sam";

char result[128] = "";                    /* this will contain the result */

++i;                                      /* increment it as you requested */
sprintf(result, "%s%03d", myString, i);   /* construct the resulting string. Note the 03 part that indicates that the integer has to be printed with a width of 3, and prepended with zero's if needed */

puts(result);                             /* show the result */
Random Solutions  
 
programming4us programming4us