1

I have a proplem , like :

Ex : MessageBoxW(0,L"Đây là ABC (This is ABC)",L"Lỗi (Error)",0);

All ok ! But i want to replace ABC to variable , like it : char buff[500]; char author[] = "ABC"; sprintf_s(buff,"Đây là %s (This is %s)",author); MessageBoxW(0, WHAT WILL BE HERE,L"Lỗi (Error)",0);

I hope someone may help !

EddyLee
  • 803
  • 2
  • 8
  • 26
  • `MessageBoxW` requires a wide string. – Retired Ninja Jan 01 '15 at 11:57
  • 1
    Take a look at the CString class. http://msdn.microsoft.com/en-us/library/aa315043%28v=vs.60%29.aspx. It allows you to format the string with the format memberfunction and supports LPCTSTR to pass to the messagebox – Unimportant Jan 01 '15 at 11:57

1 Answers1

1

You can certainly display a variable, but it has to be of the correct type. MessageBoxW takes a LPCWSTR (wide), and a char[] provides a LPCSTR (narrow) instead. So swap out the types accordingly:

WCHAR buff[500];                                      // WCHAR not char
WCHAR author[] = L"ABC";                              // WCHAR not char
swprintf_s(buff, L"Đây là %s (This is %s)", author);  // swprintf_s not sprintf_s
MessageBoxW(0, buff, L"Lỗi (Error)", 0);

It's also a good idea to avoid the raw buffers and use a wrapper class such as ATL::CStringW or std::wstring.


(I had some trouble deciding whether to answer this. The related question Why can't I display this string on MessageBox? seems like a duplicate, but it's closed as a duplicate of Cannot convert parameter from 'const char[20]' to 'LPCWSTR' which does not answer this question. In fact its answer is included in this question.)

Community
  • 1
  • 1
Michael Urman
  • 15,737
  • 2
  • 28
  • 44