When I draw on the screen I want to show a dynamic text area for the game score. The only problem is that when I redraw the screen, it is not updated with the new score value and also there is garbled characters that appear after the zero. What I am trying to do is store an int that keeps the players score and increment that int and redraw the new value on the screen.
void drawText(SDL_Surface* screen,
char* string,
int posX, int posY)
{
TTF_Font* font = TTF_OpenFont("ARIAL.TTF", 40);
SDL_Color foregroundColor = { 255, 255, 255 };
SDL_Color backgroundColor = { 0, 0, 0 };
SDL_Surface* textSurface = TTF_RenderText_Shaded(font, string,
foregroundColor, backgroundColor);
SDL_Rect textLocation = { posX, posY, 0, 0 };
SDL_BlitSurface(textSurface, NULL, screen, &textLocation);
SDL_FreeSurface(textSurface);
TTF_CloseFont(font);
}
char convertInt(int number)
{
stringstream ss;//create a stringstream
ss << number;//add number to the stream
std::string result = ss.str();//return a string with the contents of the stream
const char * c = result.c_str();
return *c;
}
score = score + 1;
char scoreString = convertInt(score);
drawText(screen, &scoreString, 580, 15);
Regarding the garbled output, it's because you use the single character you receive from convertInt
as a string by using the address-of operator (&
). The data in memory after that single character may contain anything, and most likely not the special string terminator character.
Why return a single character from the string? Use e.g. std::to_string
and return the whole std::string
, or keep using the std::stringstream
and return the string proper from that.
As for the number not being updated, it might be that you have a multi-digit number but you're only returning the first digit. Return the string, as I recommended above, and keep using std::string
in the call to drawText
, and it should probably work better.
As it seems you are not allowed to alter the drawText
function, use something like this:
score++;
// Cast to `long long` because VC++ doesn't have all overloads yet
std::string scoreString = std::to_string(static_cast<long long>(score));
drawText(screen, scoreString.c_str(), 580, 15);