Adding std::string values to CListBox ends up as gibberish

526 Views Asked by At

OK, what is wrong with this?

void CMFCApplication1Dlg::OnBnClickedOk()
{
    std::vector<std::string> vectorList;

    try
    {
        CMSAToolsLibraryWrapper wrapper;

        __int64 lResult = wrapper.SetDatabasePath(std::string("d:\\Test.xml"));
        __int64 iNumPublishersRead = 0;
        if (wrapper.ReadPublisherData(iNumPublishersRead))
        {
            vectorList = wrapper.GetPersonnelNames(true);
            for (std::string& strName : vectorList)
            {
                m_lbNames.AddString((LPCTSTR)strName.c_str());
            }
        }
    }
    catch(_com_error *e)
    {
        AfxMessageBox(_T("Problem"));
    }

    //CDialogEx::OnOK();
}

If I place a breakpoint on the AddString call the strName value is correct. But my CListBox ends up with Chinese characters. Why ?

2

There are 2 best solutions below

0
Mark Ransom On BEST ANSWER

You're sending char strings to a function that requires wchar_t strings. The (LPCTSTR) cast is masking the error message that would have told you what was wrong.

4
Andrew Truckle On

This works:

void CMFCApplication1Dlg::OnBnClickedOk()
{
    std::vector<std::string> vectorList;

    try
    {
        CMSAToolsLibraryWrapper wrapper;

        __int64 lResult = wrapper.SetDatabasePath(std::string("d:\\Test.xml"));
        __int64 iNumPublishersRead = 0;

        if (wrapper.ReadPublisherData(iNumPublishersRead))
        {
            vectorList = wrapper.GetPersonnelNames(true);
            for (std::string& strName : vectorList)
            {
                CString strName2(strName.c_str());
                m_lbNames.AddString(strName2);
            }

            UpdateData(FALSE);
        }
    }
    catch(_com_error *e)
    {
        AfxMessageBox(_T("Problem"));
    }
}

Putting the std::string into a CString first and then passing that with AddString works.