Search code examples
c++winapimessagebox

How to convert type "int" to type "LPCSTR" in Win32 C++


Hello friends how can I convert type "int" to type "LPCSTR"? I want to give the variable "int cxClient" to the "MessageBox" function's second parameter "LPCSTR lpText". Following is the sample code:

int cxClient;    
cxClient = LOWORD (lParam);    
MessageBox(hwnd, cxClient, "Testing", MB_OK);

But it does not work. The following function is the method signature of the "MessageBox" function:

MessageBox(HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType);

Solution

  • Convert the int to a string by using the right sprintf variant

    TCHAR buf[100];
    _stprintf(buf, _T("%d"), cxClient);
    MessageBox(hwnd, buf, "Testing", MB_OK);
    

    you need <tchar.h>.

    I think _stprintf is the quick answer here - but if you want to go pure C++ like David suggests, then

    #ifdef _UNICODE
    wostringstream oss;
    #else
    ostringstream oss;
    #endif
    
    oss<<cxClient;
    
    MessageBox(0, oss.str().c_str(), "Testing", MB_OK);
    

    You need

    #include <sstream>
    using namespace std;