Why can't I display this string on MessageBox?

2019-09-21 07:13发布

问题:

This question already has an answer here:

  • Cannot convert parameter from 'const char[20]' to 'LPCWSTR' 3 answers

I've created a pointer pointing to a couple of chars but after assigning it to some value and then trying to print it on the MessageBox and compiling it is giving me some errors.My code is given below:

 #include <Windows.h>
 #include <string.h>
 #include <iostream>
 using namespace std;

 void main()
 {

  char buff[100];
  string id = "ST_5";
  sprintf_s(buff, "id: %s", id.c_str());


   MessageBox(NULL, buff,L"User-id", MB_OK);

 }

Please help me in finding the problem in this code, Thanks.

My compiler's output: c:\users\zafri\documents\visual studio 2012\projects\test3\test3\test3.cpp(19): error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'char [100]' to 'LPCWSTR' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

回答1:

You should read the compiler error messages.

The second and third arguments to MessageBox have to have the same type. Either you call MessageBoxA with two char *, or you call MessageBoxW with two wchar_t *.

One fix for your code would be to do MessageBoxA(NULL, buff, "User-id", MB_OK).

You are using sprintf_s incorrectly too, please read its documentation. IMHO it would be better to use the standard function snprintf:

snprintf(buff, sizeof buff, "%s", id.c_str());

Note that you could do away with buff entirely and write:

MessageBoxA(NULL, id.c_str(), "User-id", MB_OK);


回答2:

You should use wchar_t type for all variables, objects and functions, this code works:

 #include <Windows.h>
 #include <string.h>
 #include <iostream>
 using namespace std;

 int main()
 {

  wchar_t buff[100];
  wstring id = L"ST_5";
  swprintf_s(buff, 100, L"id: %s", id.c_str());
  MessageBoxW(NULL, buff,L"User-id", MB_OK);

 }

The function swprintf_s() is the wchar_t/safe version of the sprintf/snprintf

Ciao



回答3:

For the second argument of MessageBox you use chars, while for the third one you use wchar_ts. This is wrong. If you build not for UNICODE, remove L from L"User-id" so it becomes char array.