Search code examples
c++stringvisual-studio-2008visual-c++messagebox

Use of MessageBoxW in Visual C++ to output multiple strings which are added together


How would I output a mix of different variables in a LPCWSTR to show it up in a MessageBoxW? I am using Visual C++ 2008 Express and I am a very beginner. My problem is to add different variables to a string. It basically says always: cannot add two pointers. Why I cannot add two strings or a string and an integer together with the regular "+" sign like in all other programming languages? I used Google and found stringstream, but this did not worked out for me, so please don't suggest it anymore to me.

I have this three types of variables: (Yes, my program runs with unicode and it has to be that way! I have defined unicode in the header.)

wchar_t username[255];
wchar_t windir1[MAX_PATH];
wchar_t computername1[255];

Then I have a variable for my MessageBox:

LPCWSTR message1;

And I have the code for my MessageBox:

MessageBox(NULL, message1, L"Info", MB_OK);

How would I add now all three variables together to output. My following code doesn't work:

message1 = "Computername: " + computername1 + "\n" + "Username: " + username1 + "\n" + "Windows Directory: " + windir1;

The error is something like "cannot convert..." and "cannot add two pointers..." I tried already everything or the plus sign ('+') is illegal. Is there any text macro to add strings easily together or something similar? I found nothing satisfying on my research. Most examples where for Borland like .c_str() which isn't available with Visual Studio C++.

One variable works for output as long is not anything added to it:

LPCWSTR message1 = _T(computername1);

But how I said I would like to put out "message1" with the plus operator and multiple strings added together.

This construct already doesn't work it says: Cannot add two pointers!

LPCWSTR message1 = _T(computername1) + _T("My Test String");

What pointers?


Solution

  • Addition will not work.

    You must allocate memory and copy your string elsewhere. A good way is wsprintf, or a C++ class std::wstring which does support addition. However, it is better to avoid widechars (UTF-16) and do the addition with a regular std::string. Pass them to MessageBoxW() with boost::nowide. For more details, please see utf8everywhere.org.