Home > OS >  What am I missing to make this int to char conversion produce the intended effect?
What am I missing to make this int to char conversion produce the intended effect?

Time:06-08

I am making a game in SDL2, and I've decided to add an FPS counter. The number for the counter needs to update every second, and here's how I've accomplished that

bool updateFPS() {
        if (fpsDTime == 1) {   // time between update has been one second
            frameCounterS  ;   // add an extra frame
    
            fpsTime = currentTime;   // reset timer

            // My attempt at converting my int to a char to display             

            char SframeCounterS[MAX_DIGITS   sizeof(char)];

            std::to_chars(SframeCounterS, SframeCounterS   MAX_DIGITS, frameCounterS);
    
            // Rendering the text

            message = TTF_RenderText_Blended(HPusab, SframeCounterS, White);   // Loading text to a variable

            std::cout << SframeCounterS << std::endl;   // Console Debugging

            if (message == NULL) {
                std::cout << "Could not create message! " << SDL_GetError() << std::endl;
                return false;
                // code will stop running here because I used a return statement
            }   // Error Checking Function

            slotEight = SDL_CreateTextureFromSurface(gRenderer, message);   // Creating a texture from my surface

            if (slotEight == NULL) {
                std::cout << "Could not create Message! " << SDL_GetError() << std::endl;
                return false;
                // code will stop running here because I used a return statement
            }   // More error checking!

            rslotEight.x = 30;  // controls the rect's x coordinate 
            rslotEight.y = 10; // controls the rect's y coordinte
            rslotEight.w = message->w; // controls the width of the rect
            rslotEight.h = message->h; // controls the height of the rect

            frameCounterS = 0;   // Reset the FPS counter
}

The reason I am trying to convert to a char and not a string is because the TTF_RenderText method requires a char as input for the text. It does display the numbers like I want it to, but it has a bunch of garbage characters at the end.

Here's my console output: Console Output with garbage characters

CodePudding user response:

I suspect you're just seeing uninitialized bytes from SframeCounterS. You should either clear the buffer with a memset(SframeCounterS, 0, sizeof(SframeCounterS));, or work with a string, which would simplify the code as well:

TTF_RenderText_Blended(HPusab, std::to_string(frameCounterS).c_str(), White);
  • Related