Search code examples
c++winapitchar

Concatenate LPCTSTR for MessageBox


How do I concatenate LPCTSTRs for the MessageBox? The syntax in Java is like this

LPCTSTR str1 = "String2";
LPCTSTR str2 = "";
LPCTSTR str3 = "String1";
LPCTSTR finalMsg = "";

finalMsg = str1 + str2 + str3;

What is the syntax in C++/Win32? Thanks!


Solution

  • #include <windows.h>
    #include <tchar.h>
    
    int main()
    {
        LPCTSTR str1 = _T("String2");
        LPCTSTR str2 = _T("");
        LPCTSTR str3 = _T("String1");
    
        LPTSTR finalMsg = new TCHAR[_tcslen(str1) + _tcslen(str2) + _tcslen(str3) + 1];
        _tcscpy(finalMsg, str1);
        _tcscat(finalMsg, str2);
        _tcscat(finalMsg, str3);
    
        MessageBox(nullptr, finalMsg, _T("Message"), MB_OK);
    
        delete[] finalMsg;
    }
    

    Plan-B: Use the std string classes:

    #include <windows.h>
    #include <tchar.h>
    
    #include <string>
    
    using tstring = std::basic_string<TCHAR>;
    
    int main()
    {
        tstring str1 = _T("String2");
        tstring str2 = _T("");
        tstring str3 = _T("String1");
    
        tstring finalMsg = str1 + str2 + str3;
    
        MessageBox(nullptr, finalMsg.c_str(), _T("Message"), MB_OK);
    }
    

    If you don't need to support ANSI-only versions of Windows, you can drop TCHAR and ...TSTR altogether and use std::wstring, which is a template specialization of std::basic_string for wchar_t.