将Int转换为char *并显示在屏幕上
Converting Int to char * and displaying on screen
当我在屏幕上绘制时,我想要显示游戏分数的动态文本区域。唯一的问题是,当我重新绘制屏幕时,它没有更新新的分数值,而且在零之后出现了乱码。我想要做的是存储一个int值来保持玩家的得分,并增加该int值,并在屏幕上重新绘制新值。
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);
关于混乱的输出,这是因为您使用地址操作符(&
)将从convertInt
接收到的单个字符用作字符串。该字符之后的内存数据可以包含任何内容,很可能不是特殊的字符串结束符。
为什么从字符串返回一个字符?例如,使用std::to_string
并返回整个std::string
,或继续使用std::stringstream
并返回相应的字符串。
对于没有更新的号码,可能是您有一个多位数的号码,但您只返回第一个数字。返回字符串,正如我上面建议的那样,并在调用drawText
时继续使用std::string
,它应该可以更好地工作。
似乎你不允许改变drawText
函数,使用这样的东西:
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);
相关文章:
- Winapi:屏幕截图未显示在窗口中
- 如何在快板的屏幕中显示子位图的绘制?
- SFML 中的字体.信息不显示在屏幕上.显示的不是信息,而是点
- 如何使用 openGL 在屏幕上显示加载的纹理
- 如何使用方法覆盖在输出屏幕上显示堆栈整数值
- 如何使用TouchGFX在LCD屏幕上显示ADC值
- 为什么屏幕上显示了一半的三角形
- 如何在屏幕上显示对象列表?
- C++列出屏幕以在第二台显示器中显示图像
- 显示和隐藏Windows 10屏幕键盘(osk.exe)时遇到问题
- 将25个甚至整数存储到一个名为intlist的整数阵列中,然后在屏幕上显示数组,并在屏幕上显示名为fivintegers
- QML强制窗口将在第一个屏幕上显示
- 如何使用OpenGL在屏幕上显示三角形
- 从文本文件中读取行并显示在屏幕上
- 我的程序没有将字符显示在屏幕上
- 在屏幕上显示矢量
- 在同一屏幕上显示两个不同的对象
- 屏幕显示脚本中'.'令牌之前的预期非限定 id
- C / SFML:使用两个递归调用在屏幕上打印凸形形状仅显示第一个递归调用中的形状,而不是第二个
- 如果我使用的是迭代器,为什么在c++中没有屏幕显示呢