Display a Variable in MessageBox c++
Create a temporary buffer to store your string in and use sprintf
, change the formatting depending on your variable type. For your first example the following should work:
char buff[100];
string name = "stackoverflow";
sprintf_s(buff, "name is:%s", name.c_str());
cout << buff;
Then call message box with buff as the string argument
MessageBox(hWnd, buff, "Msg title", MB_OK | MB_ICONQUESTION);
for an int change to:
int d = 3;
sprintf_s(buff, "name is:%d",d);
This can be done with a macro
#define MSGBOX(x) \
{ \
std::ostringstream oss; \
oss << x; \
MessageBox(oss.str().c_str(), "Msg Title", MB_OK | MB_ICONQUESTION); \
}
To use
string x = "fred";
int d = 3;
MSGBOX("In its simplest form");
MSGBOX("String x is " << x);
MSGBOX("Number value is " << d);
Alternatively, you can use varargs (the old fashioned way: not the C++11 way which I haven't got the hang of yet)
void MsgBox(const char* str, ...)
{
va_list vl;
va_start(vl, str);
char buff[1024]; // May need to be bigger
vsprintf(buff, str, vl);
MessageBox(buff, "MsgTitle", MB_OK | MB_ICONQUESTION);
}
string x = "fred";
int d = 3;
MsgBox("In its simplest form");
MsgBox("String x is %s", x.c_str());
MsgBox("Number value is %d", d);