Mail Archives: djgpp/1998/07/28/14:13:00
On 28 Jul 98 at 18:43, Niki Ruusunko wrote:
> I have this problem with a function I use to do thousands separators to
> integers. Here is the code:
[snipped]
> It isn't very good function but it works (on ints that is). The problem is
> that I need it to support the "long long" -variables I use. Sprintf doesn't
> compile with a long long as the argument (it says: "warning: int format,
> different type arg (arg 3)") so I'm asking if there is an alternate
> function to make a string out of an int (or, a long long in this case).
According to the docs ("info libc a printf"), you can use the `L' or `ll'
conversion qualifiers to specify long long integers, i.e.:
sprintf (s, "%lld %Ld", x, x);
where x is a long long and s is a pointer to some chars; this should
print the same number twice.
> Of course, if you know how to make the separators some better way, please
> tell me.
This is shorter:
void go (unsigned long long x)
{
if (x / 1000) {
go (x / 1000);
printf (",%03d", (int)(x % 1000));
} else {
printf ("%d", (int)(x % 1000));
}
}
If you want it to print to memory instead, try this: (untested)
char *go (unsigned long long x, char *s)
{
char *retval = s;
if (x / 1000) {
go (x / 1000, s);
while (*s) s++;
sprintf (s, ",%03d", (int)(x % 1000));
} else {
sprintf (s, "%d", (int)(x % 1000));
}
return retval;
}
Make sure the buffer you pass is large enough. Like many string
functions, it returns the pointer you pass.
--
george DOT foot AT merton DOT oxford DOT ac DOT uk
- Raw text -