Using character callback

Using GLFW
VSZM
2013-09-21
2013-09-22
  • VSZM
    VSZM
    2013-09-21

    Hello! I haven't been able to find any examples on how to implement a character callback function, so I am here to ask for review about my implementation. I want to store all the printable characters in a std::wstring if the player has opened the chat window. This is how I implemented the function, but it seems kind of stupid to me:

    http://pastebin.com/zhUcmsS5

    Can you guys tell me a better way to do this?

     
  • Doug Binks
    Doug Binks
    2013-09-22

    Copying the code you linked to below to make this easier to follow:

    void Text_Callback(GLFWwindow* window,unsigned int character)
    {
        if(this_shared->is_chatting)
        {
            wchar_t* input = new wchar_t[1];
            input[0]=character;
            std::wstring ws(input);
            this_shared->game_logic->chat_buffer->insert(this_shared->game_logic->chat_cursor_pos,input);
            delete [] input;
        }
    }
    

    This can indeed be simplified. There isn't a constructor for wstring which takes a single character, so you need to append as follows:

    void Text_Callback(GLFWwindow* window,unsigned int character)
    {
        if(this_shared->is_chatting)
        {
            std::wstring ws;
            ws += character;
            this_shared->game_logic->chat_buffer->insert(this_shared->game_logic->chat_cursor_pos,input);
        }
    }
    

    Note that your original code has a buffer overrun issue as the array 'input' does not have a null terminator. You need to have it one longer than the characters inside with a 0 at the end. Additionally you don't need to 'new' a small array, you can declare it on the stack as: 'wchar_t input[2];', and that way you don't have to delete it.

     
    • VSZM
      VSZM
      2013-09-22

      Thanks for your reply.

      Yes there were a lot of unwanted memory garbage inserted to my string, beacuse of the lack of null terminator.

      I used pastebin, because I was not able to find a clear example of how to insert code on the 'Formatting Help' page. Can you clarify this to me?

       
  • Doug Binks
    Doug Binks
    2013-09-22

    Also worth noting you could simplify things by having a function for chat buffer which takes a single character as input.

     
  • Doug Binks
    Doug Binks
    2013-09-22

    To format for code I put a line of six '~' characters before and after the code, with empty lines before and after the block. So:

    [empty line]
    [line of six ~]
    [Code... as many lines as you want]
    [line of six ~]
    [empty line]