1

画面に描画するときに、ゲーム スコアの動的テキスト領域を表示したいと考えています。唯一の問題は、画面を再描画すると、新しいスコア値で更新されず、ゼロの後に表示される文字化けがあることです。私がやろうとしているのは、プレーヤーのスコアを保持する 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);
4

1 に答える 1

3

出力が文字化けしているのconvertIntは、アドレス演算子 ( &) を使用して、受け取った単一の文字を文字列として使用しているためです。その単一文字の後のメモリ内のデータには何でも含まれる可能性があり、特殊な文字列ターミネータ文字ではない可能性が最も高いです。

文字列から 1 文字を返すのはなぜですか? egstd::to_stringを使用して全体を返すstd::stringか、を使用し続けてstd::stringstreamそこから適切な文字列を返します。

更新されていない番号については、複数桁の番号を持っている可能性がありますが、最初の桁のみを返しています。上記で推奨したように文字列を返し、std::stringの呼び出しで使用し続けるdrawTextと、おそらくよりうまく機能するはずです。


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);
于 2013-01-02T00:11:22.270 に答える