将Int转换为char *并显示在屏幕上

Converting Int to char * and displaying on screen

本文关键字:显示 屏幕 Int 转换 char      更新时间:2023-10-16

当我在屏幕上绘制时,我想要显示游戏分数的动态文本区域。唯一的问题是,当我重新绘制屏幕时,它没有更新新的分数值,而且在零之后出现了乱码。我想要做的是存储一个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);