View previous topic :: View next topic |
Author |
Message |
Audi80
Joined: 07 Sep 2007 Posts: 41
|
String format with leading zeros (0)... |
Posted: Thu Aug 05, 2010 9:25 am |
|
|
Hi there, does anyone know how I can format a string with leading zeros:
Ex:
Code: |
char a[200] = "Hi there";
char b[200] = "";
sprintf(b,"%021s",b);
//// Result : b = "0000000000000Hi there";
|
I can do it this way in a normal compiler (cygwin)...
But with CCS doesn't seem to work.
Thanks in advance. |
|
![](templates/subSilver/images/spacer.gif) |
collink
Joined: 08 Jan 2010 Posts: 137 Location: Michigan
|
Re: String format with leading zeros (0)... |
Posted: Thu Aug 05, 2010 10:30 am |
|
|
How about using memset? If you already know how many zeros you want you could do something like:
Code: |
memset(b, '0', 21);
|
And then use strcat to combine them
Audi80 wrote: | Hi there, does anyone know how I can format a string with leading zeros:
Ex:
Code: |
char a[200] = "Hi there";
char b[200] = "";
sprintf(b,"%021s",b);
//// Result : b = "0000000000000Hi there";
|
I can do it this way in a normal compiler (cygwin)...
But with CCS doesn't seem to work.
Thanks in advance. |
|
|
![](templates/subSilver/images/spacer.gif) |
Audi80
Joined: 07 Sep 2007 Posts: 41
|
|
Posted: Thu Aug 05, 2010 11:10 am |
|
|
Hi there, I cant use strcat because it concatenates two strings and the result would be:
000000000000000000000Hi There...
I made it the following way which is not the most elegant way to do it:
Code: |
static unsigned int i = 0,j=0;
memset(auxCard,0,sizeof(auxCard));
sprintf(auxCard,"0000000000000000000");
j=strlen(cartao);
for(i = 20;j>0;--i){
auxCard[i] = cartao[--j];
}
return auxCard;
|
But... it works... ![Wink](images/smiles/icon_wink.gif) |
|
![](templates/subSilver/images/spacer.gif) |
Wayne_
Joined: 10 Oct 2007 Posts: 681
|
|
Posted: Fri Aug 06, 2010 1:34 am |
|
|
Try
Code: |
#define MAX_LEN 21
char a[200] = "Hi there";
char b[200];
memset(b, '0', MAX_LEN); // This will not null terminate the string!
b[MAX_LEN] = '\0';
strcpy(b + MAX_LEN - strlen(a), a);
|
I havn't tested it but it should work. |
|
![](templates/subSilver/images/spacer.gif) |
Ttelmah
Joined: 11 Mar 2010 Posts: 19381
|
|
Posted: Fri Aug 06, 2010 2:21 am |
|
|
The 'leading zeros', for a string, with the other C you have tried, is _not_ standard. If you read the K&R manuals, you will find that '0' as a modifier, specifically says "for numeric conversions". So CCS omitting this, is really 'correct'!...
I'd suggest:
Code: |
char a[200] = "Hi there";
char b[200];
int8 ctr;
for (ctr=0;ctr<(21-strlen(a));ctr++) b[ctr]='0';
sprintf(b+ctr,"%s",a);
|
Best Wishes |
|
![](templates/subSilver/images/spacer.gif) |
|