Reputation: 445
How to display a Variable in MessageBox c++ ?
string name = "stackoverflow";
MessageBox(hWnd, "name is: <string name here?>", "Msg title", MB_OK | MB_ICONQUESTION);
I want to show it in the following way (#1):
"name is: stackoverflow"
and this?
int id = '3';
MessageBox(hWnd, "id is: <int id here?>", "Msg title", MB_OK | MB_ICONQUESTION);
and I want to show it in the following way (#2):
id is: 3
how to do this with c++ ?
Upvotes: 9
Views: 89490
Reputation: 180145
It's not good to see people still messing with buffers. That was unnecessary in 1998, and definitely today.
std::string name = "stackoverflow";
MessageBox(hWnd, ("name is: "+name).c_str(), "Msg title", MB_OK | MB_ICONQUESTION);
If you're using Unicode (which makes sense in the 21st century)
std::wstring name = L"stackoverflow";
MessageBox(hWnd, (L"name is: "+name).c_str(), L"Msg title", MB_OK | MB_ICONQUESTION);
Upvotes: 1
Reputation: 458
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);
Upvotes: 10
Reputation: 136
This is the only one that worked for me:
std::string myString = "x = ";
int width = 1024;
myString += std::to_string(width);
LPWSTR ws = new wchar_t[myString.size() + 1];
copy(myString.begin(), myString.end(), ws);
ws[myString.size()] = 0; // zero at the end
MessageBox(NULL, ws, L"Windows Tutorial", MB_ICONEXCLAMATION | MB_OK);
Upvotes: 1
Reputation: 8289
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);
Upvotes: 3
Reputation: 135
Answer to your question:
string name = 'stackoverflow';
MessageBox("name is: "+name , "Msg title", MB_OK | MB_ICONQUESTION);
do in same way for others.
Upvotes: 0