problem with number formatting code.

Posted by Typhon on Sun 05 Oct 2008 04:23 PM — 5 posts, 23,142 views.

USA #0
seems like i'm missing something real small here but nonetheless i cant find it.
added :

char *short_num(int num)
{
	static char buf[12];
	buf[0] = '\0';
	
	if (num <= 9999)
	{
		sprintf(buf, "%d", num);
		return buf;
	}
	sprintf(buf, "%5.1f%c", (float)num / 1000, num>1000000 ? 'm' : 'k' );
	return buf;
}


when calling that function in
ch_printf(ch, "%-4s/%-4s ", short_num(ch->hit), short_num(ch->max_hit) ); 


it returns the exact same figure for both :(
11.4k/11.4k when ch has 30,000 max_hit.
thanks
-typ
USA #1
This may be related, but in Smaug if you use num_punct (which does the same thing) on the same line, it won't work.
USA #2
haha breaking up the code works. thanks :)
USA #3
static char buf[12];

Although you figured it out, I'd like to point out it is the use of a static variable that causes this. It avoids memory allocation management, but at the expense of situations like this. As you have discovered, it works if you break up the code calling the functions.

If I had to guess, the value retained in the buffer is from the last call completed since the return value each time points to the same static character array. Because you put two calls in one line, the second call was stacked on the first call, thus executing the second call first, causing it's value in 'buf' to be wiped out by the next call.
Amended on Mon 06 Oct 2008 06:01 AM by Nick Cash
Australia Forum Administrator #4
You would be 100% correct about that.