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

10,391

Solution 1

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;

Solution 2

using std::to_string

std::string message = std::to_string(cxClient)

http://en.cppreference.com/w/cpp/string/basic_string/to_string

Share:
10,391
Bhaddiya Tanchangya
Author by

Bhaddiya Tanchangya

Updated on June 05, 2022

Comments

  • Bhaddiya Tanchangya
    Bhaddiya Tanchangya almost 2 years

    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);
    
  • David Heffernan
    David Heffernan almost 11 years
    Since the question is tagged C++, perhaps a C++ answer would be better
  • David Heffernan
    David Heffernan almost 11 years
    Note that std::to_string requires C++11
  • user93353
    user93353 almost 11 years
    @DavidHeffernan - adding one with ostringstream also.
  • Bhaddiya Tanchangya
    Bhaddiya Tanchangya almost 11 years
    Wow! I got it. Now the "MessageBox" function can display the variable I want :D . Following is my working code: #include <sstream> using namespace std; #ifdef _UNICODE wostringstream oss; #else ostringstream oss; #endif oss<<cxClient; MessageBox(hwnd, oss.str().c_str(), "Testing", MB_OK); Thank you so much :D
  • IInspectable
    IInspectable almost 11 years
    @Bhaddiya Instead of the conditional code you could also use typedef std::basic_ostringstream<TCHAR> tostringstream. Alternatively use wostringstream together with the UNICODE-variant MessageBoxW.