在呈现文本C++时显示变量SDL_TTF
Display a variable while rendering SDL_TTF text C++
需要使用 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);
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- SDL 带变量的多线程处理 -- 无法按预期工作
- SDL:制作静态文本变量
- C++SDL,变量在未初始化的情况下被使用
- SDL 无法在没有常量变量的情况下创建矩形数组