在MessageBox C 中显示一个变量

Display a Variable in MessageBox c++

本文关键字:一个 变量 MessageBox 显示      更新时间:2023-10-16

如何在MessageBox C ?

中显示变量
string name = "stackoverflow";
MessageBox(hWnd, "name is: <string name here?>", "Msg title", MB_OK | MB_ICONQUESTION);

我想以以下方式显示(#1):

"name is: stackoverflow"

和这个?

int id = '3';
MessageBox(hWnd, "id is: <int id here?>", "Msg title", MB_OK | MB_ICONQUESTION);

我想以以下方式显示(#2):

id is: 3

如何使用C ?

进行此操作

创建一个临时缓冲区以存储您的字符串并使用sprintf,请根据变量类型更改格式。对于您的第一个示例,以下应有效:

 char buff[100];
 string name = "stackoverflow";
 sprintf_s(buff, "name is:%s", name.c_str());
 cout << buff;

然后用buff呼叫消息框,为字符串参数

MessageBox(hWnd, buff, "Msg title", MB_OK | MB_ICONQUESTION);

int更改为:

int d = 3;
sprintf_s(buff, "name is:%d",d);

这可以用宏

完成
#define MSGBOX(x) 
{ 
   std::ostringstream oss; 
   oss << x; 
   MessageBox(oss.str().c_str(), "Msg Title", MB_OK | MB_ICONQUESTION); 
}

使用

string x = "fred";
int d = 3;
MSGBOX("In its simplest form");
MSGBOX("String x is " << x);
MSGBOX("Number value is " << d);

另外,您可以使用varargs(老式的方式:不是我尚未掌握的C 11方法)

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

这是唯一对我有用的人:

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

看到人们仍在弄乱缓冲区是不好的。那是1998年,肯定是不必要的。

std::string name = "stackoverflow";
MessageBox(hWnd, ("name is: "+name).c_str(), "Msg title", MB_OK | MB_ICONQUESTION);

如果您使用的是Unicode(在21世纪很有意义)

std::wstring name = L"stackoverflow";
MessageBox(hWnd, (L"name is: "+name).c_str(), L"Msg title", MB_OK | MB_ICONQUESTION);

回答您的问题:

字符串名称='stackoverflow';

MessageBox("名称为:" 名称," msg title",mb_ok | mb_iconquestion);

对他人以相同的方式做。