Cannot convert parameter 1 from 'const wchar_t *' to 'LPCTSTR' in an MFC / C ++ project

I get a compilation error in the line:

MessageBox(e.getAllExceptionStr().c_str(), _T("Error initializing the sound player")); Error 4 error C2664: 'CWnd::MessageBoxA' : cannot convert parameter 1 from 'const wchar_t *' to 'LPCTSTR' c:\users\daniel\documents\visual studio 2012\projects\mytest1\mytest1\main1.cpp 141 1 MyTest1 

I do not know how to solve this error, I tried the following:

 MessageBox((wchar_t *)(e.getAllExceptionStr().c_str()), _T("Error initializing the sound player")); MessageBox(_T(e.getAllExceptionStr().c_str()), _T("Error initializing the sound player")); 

I use the "Use multibyte character set" option and I do not want to change it.

+5
source share
4 answers

The easiest way is to simply use MessageBoxW instead of MessageBox .

 MessageBoxW(e.getAllExceptionStr().c_str(), L"Error initializing the sound player"); 

The second easiest way is to create a new CString from the original; It will automatically convert to / from wide string and MBCS string if necessary.

 CString msg = e.getAllExceptionStr().c_str(); MessageBox(msg, _T("Error initializing the sound player")); 
+5
source

LPCSTR = const char* . You pass it const wchar* , which is clearly not the same.

Always verify that you are passing API functions to the correct parameters. _T("") type C-strings are wide strings and cannot be used with this version of MessageBox() .

+1
source

Since e.getAllExceptionStr().c_str() returns a wide string, then the following will work:

MessageBoxW(e.getAllExceptionStr().c_str(), L"Error initializing the sound player");

Note the W at the end of MessageBoxW ;

+1
source

If you want to compile in legacy MBCS mode, you can use ATL / MFC string conversion helpers , for example CW2T , for example:

 MessageBox( CW2T(e.getAllExceptionStr().c_str()), _T("Error initializing the sound player") ); 

It seems your getAllExceptionStr() method returns std::wstring , so calling .c_str() on it returns const wchar_t* .

CW2T converted from wchar_t -string to TCHAR -string, which in your case (considering MBCS compilation mode) is equivalent to char -string.

Note, however, that conversions from Unicode ( wchar_t -strings) to MBCS ( char strings) may be lost.

0
source

Source: https://habr.com/ru/post/1214993/


All Articles