Click to See Complete Forum and Search --> : Format...iomanip?
The Hobo
Apr 11th, 2002, 11:19 AM
I have a series of double variables, that can be anything from 0.00, to 000.00. What I want is to add leading zeros so that they all line up:
From:
$ 5.66
$ 12.12
$ 122.42
to something like:
$ 005.66
$ 012.12
$ 122.42
or better yet, a way to do:
$ 5.66
$ 12.12
$ 122.42
(forums messed up the spacing, sorry)
any ideas?
jim mcnamara
Apr 11th, 2002, 02:13 PM
You want this in C?
try:
void lpad(char *src, char *dest, int *length){
char *buf;
char *s;
memset(dest,0x0, (size_t) length +1);
memset(dest,0x20,(size_t) length);
buf = src;
buf += strlen(src);
s = dest;
s+= length;
while((int) buf >= (int) src){
*s-- = *buf--;
}
return;
}
The Hobo
Apr 11th, 2002, 10:25 PM
Not sure I follow this? :confused:
jim mcnamara
Apr 12th, 2002, 03:35 PM
This is an example of how to blank-fill something.
You convert a number to a char like this:
void tochar(float src, char *dest){ // convert a float to a char
sprintf(dest,"%f",src);
}
This left pads a char to a given length
void lpad(char *src, char *dest, int *length){ // fill in leading blanks
char *buf; // char pointer
char *s;
memset(dest,0x0, (size_t) length +1); // initalize the destination
memset(dest,0x20,(size_t) length);
if (strlen(src)>=length){
strcpy(dest,src);// the src is >= length
}
else{ // src neds to be padded.
buf = src; // start at the beginning of the source string
buf += strlen(src); // go to the end
s = dest; // start at the beginning
s+= length; // go to the end of the source
while((int) buf >= (int) src){
*s-- = *buf--; // stuff all the
} // source chars into the dest
} // working back to front
return;
}
usage:
float f;
char *buf;
char result[20];
memset(result,0x00,sizeof(result);
f = 18.3 * 4;
tochar(f,result);
lpad(result,19);
result[0]='$';
printf("%s\n",result);
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.