Display a Variable in MessageBox c++

a7md0 picture a7md0 · Feb 7, 2014 · Viewed 49.7k times · Source

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

Answer

Gibby picture Gibby · Feb 7, 2014

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