0

I'm trying to make a score display in openGL for a game. For the text I'm using:

void draw_text(const char* text)
{
    size_t len = strlen(text);
    for (size_t i=0;i<len;i++)
    {
        glutStrokeCharacter(GLUT_STROKE_ROMAN, text[i]);
    }
}

If I pass in the text made like so:

const char* score_text = "Score:";

It displays it correctly on the screen, however I want a variable number score so I'm converting an int to a const char* like so:

// converts int to string
const char* int_to_string(int i)
{
    std::ostringstream str1;
    str1 << i;
    std::string temp = str1.str();

    return temp.c_str();
}

I have tried to_string and the system I'm on has a bug stopping it from working (it's a marked piece so it has to run on the provided system) so I am using the above method.

now if I pass the number to the draw_text:

draw_text(int_to_string(180));

It will print out the first character fine but the rest seem to get corrupted such that they do not appear or appear as a different character. e.g. "1K" or "1cp"

I can't seem to find the cause from a quick google, however I have found if I send the char to cout after passing it to glutStrokeCharacter then send endl to cout then the number will display correctly. If I do the same but omit the endl, the corruption still occurs and prints to the terminal as corrupted aswel.

  • 3
    `return temp.c_str();` undefined behavior right there. – UKMonkey Jan 02 '18 at 15:10
  • @UKMonkey what do you mean undefined behavior? My understanding is that that will return the const char* for the temp string? Which seems to be what I want. – Zacarian Itari Jan 02 '18 at 15:14
  • https://stackoverflow.com/questions/22330250/how-to-return-a-stdstring-c-str should help – UKMonkey Jan 02 '18 at 15:15
  • 1
    It does, however since the temp string goes out of scope returned pointer is invalid. – user7860670 Jan 02 '18 at 15:15
  • In addition to UKMonkey: `std::string temp = str1.str();` makes a local storage of the formatted string. `temp.c_str()` returns the `const char*` pointer to the raw string stored in `temp`. As soon as you return from `int_to_string()` you lose the local `temp` and return a dangling pointer. You might return `temp` as `std::string` instead and retrieve the `c_str()` on caller side. – Scheff's Cat Jan 02 '18 at 15:16
  • ...as shown in the linked answer posted by UKMonkey... – Scheff's Cat Jan 02 '18 at 15:17
  • @UKMonkey Thanks that was it. – Zacarian Itari Jan 02 '18 at 15:18

0 Answers0