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

C++ 将Int转换为char*并在屏幕上显示,c++,sdl,sdl-ttf,C++,Sdl,Sdl Ttf,当我在屏幕上画图时,我想为游戏分数显示一个动态文本区域。唯一的问题是,当我重新绘制屏幕时,它不会用新的分数值进行更新,并且在零后面会出现乱码字符。我试图做的是存储一个整数,它保持玩家的分数,并增加该整数,然后在屏幕上重新绘制新值 void drawText(SDL_Surface* screen, char* string, int posX, int posY) { TTF_Font* font = TTF_OpenFont("ARIAL.TTF", 40); SDL_Color foreg

当我在屏幕上画图时,我想为游戏分数显示一个动态文本区域。唯一的问题是,当我重新绘制屏幕时,它不会用新的分数值进行更新,并且在零后面会出现乱码字符。我试图做的是存储一个整数,它保持玩家的分数,并增加该整数,然后在屏幕上重新绘制新值

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);
void drawText(SDL_表面*屏幕,
字符*字符串,
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_着色(字体、字符串、,
前底色、背景色);
SDL_Rect textLocation={posX,posY,0,0};
SDL_BlitSurface(文本表面、空、屏幕和文本位置);
SDL_自由曲面(textSurface);
TTF_关闭字体(字体);
}
字符转换整数(整数)
{
stringstream ss;//创建一个stringstream

ss关于乱码输出,这是因为您使用运算符地址(
&
)将从
convertInt
接收的单个字符用作字符串。该单个字符之后的内存中的数据可能包含任何内容,很可能不包含特殊的字符串终止符

为什么要从字符串返回单个字符?例如,使用并返回整个
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);
score++;
//强制转换为“long long”,因为VC++还没有所有重载
std::string scoreString=std::to_string(静态_cast(score));
drawText(screen,scoreString.c_str(),580,15);

我需要返回一个char*。我真的不知道怎么做。我使用的方法将char*作为参数,我无法更改它。@JonathanO,它是采用
char*
还是
const char*
?@JonathanO从
convertInt
返回
std::string
(或者使用了前面提到的
std::to_string
函数)使用
c_str
@JonathanO使用字符串调用
drawText
,然后您就可以复制它了。类似这样的东西在c++03中工作:
std::vector cstr(str.begin(),str.end());func(&cstr[0])
std::to_string(score)这给了我一个错误,说错误2错误C2668:'std::to_string':对重载函数的调用不明确请告诉我为什么-1