Jump to content
  • Advertisement
Sign in to follow this  
gapern

Printing a variable using sdl

This topic is 3790 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello. I was just curious how you are supposed to print the contents of a variable with sdl. I have previously used allegro and with that you just wrote %d followed by whatever variable you wanted to print, and you could do this more than once per string. I've been reading lazy foo's tutorials and if he explains this somewhere, I somehow missed it. I am using sdl_ttf.h.

Share this post


Link to post
Share on other sites
Advertisement
Yes there is. You have to create a char buffer and use sprintf. Then, when you want to draw the text, you use that string of characters (the buffer).... I don't think I explained that very well so here is an example:

(I am assuming you understand how to draw text because you read the tutorials):


char buf[50];
sprintf(buf, "This is the variable: %d", someVariable);
TTF_RenderText_Solid(font, buf, color);


In this case, buf is the string of chars and someVariable is the variable you want to see.

%d is used if you want to show a signed decimal integer, there are more of these specifiers for different types.
Check out this site for them and to get a full understanding of sprintf:
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf.html

Share this post


Link to post
Share on other sites
Please note that when you use the SDL_ttf rendering functions they create a new surface every time they are called and must be freed manually or you will have a memory problem quite quickly. Please see the SDL_ttf documentation on how to use these functions properly.

You will most likely have 2 different types of text you need to render, static (labels, names etc.) and dynamic (score, power etc.). Generating the new surfaces and freeing them every frame is not very practical especially if your game uses mostly static text or the text does not change very often. Try rendering the text only when it changes and saving the surface to be reused if you can. If the text is constantly changing like a score, you may want to render the characters "0123456789" to a surface in the font and color you wish to use and use that as a sprite sheet to draw the numbers from in the order that you need to create the score.

Your mileage will vary with this depending on the type of game but the concept is one you should consider regardless.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!