Formatting a string on a variadic parameter function without using GC

David G. Maziero via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Mar 1 17:39:13 PST 2016


Hi. I think it's the first time I post here.
I've been flirting with D for some time, but now I decided to 
start a little project.

Consider the following function:

void RenderText( FontBMP font, int x, int y, const char* text )
{
	SDL_Rect rect1, rect2;
	rect2.x = x;
	rect2.y = y;
	rect2.w = font.width;
	rect2.h = font.height;
	rect1.w = font.width;
	rect1.h = font.height;
	for( int r=0; text[r]!='\0'; ++r )
	{
		char letter = text[r];
		rect1.x = font.width*(letter%font.horizontal_count);
		rect1.y = font.height*(letter/font.horizontal_count);
		if( letter>=33 ) SDL_RenderCopy( g_renderer, font.texture, 
&rect1, &rect2 );
		rect2.x += font.spacing_x;
		if( letter==10 )
		{
			rect2.x = x;
			rect2.y += font.spacing_y;
		}
	}
}

And the use code:

	char[256] text;
	sprintf( &text[0], "Player: pos:%.3f - speed:%.3f", 
player.position, player.speed );
	RenderText( font, 0, 0, cast(char*)text );

I could simply do "RenderText(font,0,0,"FPS: "~to!string(fps));" 
but I want to avoid GC entirely.
The ideal scenario is to have something like "void RenderText( 
/*etc*/, const char* fmt, ... )" but I can't seem to figure a way 
to pass the variadic parameters to sprintf.

Any ideas?
Thanks in advance.


More information about the Digitalmars-d-learn mailing list