Jump to content
  • Advertisement
Sign in to follow this  

[SDL] Text output question

This topic is 4157 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 am currently making a pong type game using C++ and SDL. I am trying to output the player score to the screen. The player score is stored in an integer. I figured out how to output strings using the SDL_TTF library, however I cannot get an integer to output. Can anyone offer any assisance? Thanks,

Share this post

Link to post
Share on other sites
Here's how I do it. I hope it helps.

void print_text(const char *fmt, ...)
char str[256];
va_list Arg;
vsprintf(str, fmt, Arg);
SDL_Color color = {255,0,0,0};
SDL_Surface *sText = TTF_RenderText_Solid( font, str, color );
SDL_Rect rect = {0,0,0,0};
SDL_BlitSurface( sText, NULL, S, &rect );
SDL_FreeSurface( sText );
SDL_UpdateRects(S, 1, &rect);
print_text("integer: %i",i);

Share this post

Link to post
Share on other sites
Here is a sample code that I used to output an integer using SDL_TTF

// the char variable that will display the score
char text[60];

SDL_Surface * fontsurface = NULL;

TTF_Font* font = NULL;

//initialize the font
font = TTF_OpenFont("arial.ttf ", 14);

//Copy the integer variable "score" to the "text" variable which will then be blit to the surface
sprintf (text, "SCORE: %d\0",score);

fontsurface = TTF_RenderText_Solid(font,text,color);


Share this post

Link to post
Share on other sites
I would also like to add that it's smarter to store all strings in std::string strings. In CPP they're just easier to deal with, IMHO.
Here's how to use them properly:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

ostringstream oss;
oss << "Your score is: ";
int score = 5;
oss << score;
string a_string(oss.str());
fontsurface = TTF_RenderText_Solid(font, a-string.c_str() ,color);

Or, more generally to give each class this functionality (smarter);

template <class T>
std::string StringOf(T object)
std::ostringstream os;
os << object;

Share this post

Link to post
Share on other sites
Thanks for the replies. It helped tremendously. I was thinking along these same lines, but I didn't know the process to amend the original string with the integer.

Thanks again!

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!