在呈现文本C++时显示变量SDL_TTF

Display a variable while rendering SDL_TTF text C++

本文关键字:变量 SDL TTF 显示 文本 C++      更新时间:2023-10-16

需要使用 TTF 渲染文本打印出C++中的全局变量。所以它会像这样显示:

"总杀戮:"变种在这里

得到了它的工作,但它将文本推到左侧

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

这是指针算术。 它不会totalKilled转换为std::string,将其连接到"Humans killed: ",并将结果转换为以空结尾的字符串。

试试这个:

#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
    );

如果您愿意使用Boost,则可以使用lexical_cast<>而不是ToString()

如果你使用的是 c++ 11,你可以使用 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);