在MFC / C ++项目中,无法将参数1从'const wchar_t *'转换为'LPCTSTR'

时间:2015-03-09 16:13:48

标签: c++ string mfc tchar lpcwstr

我收到了一行编译错误:

 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

我不知道如何解决此错误,我尝试了以下内容:

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"));

我正在使用“使用多字节字符集”设置,我不想更改它。

4 个答案:

答案 0 :(得分:5)

最简单的方法是使用MessageBoxW代替MessageBox

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

第二种最简单的方法是从原始文件中创建一个新的CString;它会根据需要自动转换为宽字符串和MBCS字符串。

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

答案 1 :(得分:1)

LPCSTR = const char*。你传给它const wchar*,这显然不是一回事。

始终检查您是否正在向API函数传递正确的参数。 _T("")类型C字符串是宽字符串,无法与MessageBox()版本一起使用。

答案 2 :(得分:1)

e.getAllExceptionStr().c_str()返回宽字符串时,以下内容将起作用:

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

请注意W;

末尾的MessageBoxW

答案 3 :(得分:0)

如果您想在过时的MBCS模式下进行编译,您可能希望使用ATL/MFC string conversion helpers,例如 CW2T ,例如:

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

您的getAllExceptionStr()方法似乎返回std::wstring,因此在其上调用.c_str()会返回const wchar_t*

CW2Twchar_t - 字符串转换为TCHAR - 字符串,在您的情况下(考虑MBCS编译模式),相当于char - 字符串。< / p>

但请注意,从Unicode(wchar_t - 字符串)到MBCS(char - 字符串)的转换可能会有损。