R
R
rxxxxxx2020-12-28 17:05:55
C++ / C#
rxxxxxx, 2020-12-28 17:05:55

How to display variable in MessageBox?

Hello. I have a function with MessageBox. But I need to make the variable "a" appear in the contents of the messagebox. I tried to use this, but not only did the variable not appear, but half of the text disappeared somewhere:

#include <Windows.h>

int a = 10;
int DisplayResourceNAMessageBox()
{
    int msgboxID = MessageBox(
        NULL,
        (LPCTSTR)L"Resource not available\nDo you want to try again? "+a,
        (LPCTSTR)L"Account Details",
        MB_ICONWARNING | MB_OK | MB_DEFBUTTON1
    );
   return msgboxID;
}

int main()
{
   DisplayResourceNAMessageBox(); 
}


PS Example taken from the Microsoft website

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Ananiev, 2020-12-28
@SaNNy32

In order to display a variable in a MessageBox, you must convert it to a string using the itoa or sprintf functions, or use the CString class from MFC or ATL, or the std::string class from STL. https://stackoverflow.com/questions/5590381/easies...

M
Mercury13, 2020-12-28
@Mercury13

Actually, Alexander Ananiev said everything.
And I want to add.
1. You decide to compile ANSI / Unicode, but it will not be correctly converted to ANSI. Right . Although twenty-two years later, the ANSI compilation, I think, can be scored? 2. MessageBox does not imply a choice - why would a function return an int? (LPCTSTR)L"Account Details"_T("Account Details")

N
Nicholas, 2020-12-28
@romancelover

In C and C++ and WinApi, LPCTSTR is simply a pointer to a sequence of characters in memory. Adding a number to it does not change the sequence of characters, but only translates the position of the pointer. Therefore, the code in the example will output the string from the 10th character (counting from 0), and will not add a number to the string.
To achieve the desired result, you need to create a new sequence of characters and pass a pointer to it into the function. In C, you can use the functions wcscpy, wcscat and _itow (or whatever its analogue is called in your compiler) or wsprintf (inconvenient because you need to keep track of the number of characters allocated per string), in C ++ it is better to create std:: wstring (wstring since there are LPCTSTR, and long characters, and the program is built in Unicode mode), write a string and a number there (you can use wostringstream), and then pass a pointer to the MessageBox using c_str ().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question