user3463583
user3463583

Reputation: 49

Display a variable while rendering SDL_TTF text C++

Need to print out a global varible in C++ using TTF render text. So it would show like this:

"Total Killed: " Varible Here

Got this it works but it pushs the text to the left

SDL_Surface* textSurface = TTF_RenderText_Shaded(font, "Humans killed: " + totalKilled,    foregroundColor, backgroundColor);

Upvotes: 1

Views: 1997

Answers (2)

jordsti
jordsti

Reputation: 756

If you're using c++ 11, you can use std::to_string().

std::string caption_str = "Humans killed: " + std::to_string(totalKilled)

SDL_Surface* textSurface = TTF_RenderText_Shaded(font, caption_str.c_str(),    foregroundColor, backgroundColor);

Upvotes: 1

genpfault
genpfault

Reputation: 52083

"Humans killed: " + totalKilled

This is pointer arithmetic. It does not convert totalKilled to a std::string, concatenate that onto "Humans killed: ", and convert the result to a null-terminated string.

Try this instead:

#include <sstream>
#include <string>

template< typename T >
std::string ToString( const T& var )
{
    std::ostringstream oss;
    oss << var;
    return var.str();
}

...

SDL_Surface* textSurface = TTF_RenderText_Shaded
    (
    font, 
    ( std::string( "Humans killed: " ) + ToString( totalKilled ) ).c_str(),
    foregroundColor, 
    backgroundColor
    );

If you're willing to use Boost you can use lexical_cast<> instead of ToString().

Upvotes: 1

Related Questions