Jump to content
  • Advertisement
Sign in to follow this  
Ephimus

[SDL] Text output question

This topic is 3981 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
Advertisement
Here's how I do it. I hope it helps.

void print_text(const char *fmt, ...)
{
char str[256];
va_list Arg;
va_start(Arg,fmt);
vsprintf(str, fmt, Arg);
va_end(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);

SDL_BlitSurface(fontsurface,NULL,scorescreen,NULL);


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;
return(os.str());
}

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.

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

Sign me up!