Display a Variable in MessageBox c++

廉价感情. 提交于 2019-12-19 02:38:27

问题


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++ ?


回答1:


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);



回答2:


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);



回答3:


Answer to your question:

string name = 'stackoverflow';

MessageBox("name is: "+name , "Msg title", MB_OK | MB_ICONQUESTION);

do in same way for others.



来源:https://stackoverflow.com/questions/21620752/display-a-variable-in-messagebox-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!