Search code examples
stringencodingcdialog

SetDlgItemText fills edit field with junk


In my CDialog derived class, in the OnInitDialog() method, I'm pre-filling edit fields with prior configuration loaded from pre-existing config.

SetDlgItemText(IDC_EDIT1, LPCTSTR(data->project_file.c_str()));
SetDlgItemText(IDC_EDIT2, LPCTSTR(data->remote_addr.c_str()));

project_file and remote_addr are both of type std::string. They are filled correctly, with strings containing the relevant filename and hostname (checked under debugger).

The dialog items, though, display 㩆慜瑩噜獩楳屭獁整屲浴㙰䌷⹃浴⹰瑩c췍췍췍췍췍췍﷽﷽翹 and 㤱⸲㘱⸸⸰㐷촀췍 respectively. When I enter the data into them, they can be properly read, and their data converted to std::string relatively painlessly.

What am I doing wrong?


Solution

  • Since in my compilation LPCTSTR is 16 bit, std::string's 8-bit c_str() gets misinterpreted. It must be converted to wstring, and only c_str() of that sets the value correctly.

    #include <locale>
    
    void MyDialog::SetDlgItemStdString(UINT id, std::string entry)
    {
    #ifndef UNICODE
        SetDlgItemText(id, LPCTSTR(entry.c_str()));
    #else
        std::wstring_convert<std::codecvt<wchar_t, char, std::mbstate_t>> conv;
        std::wstring entry_wstring = conv.from_bytes(entry);
        SetDlgItemText(id, LPCTSTR(entry_wstring.c_str()));
    #endif
    }