错误 C2664:'callToPrint':无法将参数 1 从 'std::wstring' 转换为'LPTSTR'

error C2664: 'callToPrint' : cannot convert parameter 1 from 'std::wstring' to 'LPTSTR'

本文关键字:std wstring LPTSTR 转换 callToPrint C2664 错误 参数      更新时间:2023-10-16

我将一个窄字符串转换为宽字符串,如下所示:

string nameOfPrinter;
getline( cin , nameOfPrinter );
wstring WprinterName;
int number = MultiByteToWideChar( CP_UTF8 , 0 , nameOfPrinter.c_str() , nameOfPrinter.size() , &WprinterName , 0 );
// then i make a call to the function whose prototype is callToPrint( LPTSTR , LPVOID , DWORD , string )
// the calling statement is :
callToPrint( WprinterName , -----all other arguments-----,);
// But this call produces the following error error C2664: 'callToPrint' : cannot convert parameter 1 from 'std::wstring' to 'LPTSTR'

为什么会这样?请告诉我怎样才能解决这个问题

这里还需要使用。c_str()。

此外,我还使用

将打印机名称直接读入WprinterName。
getline(wcin, Wprintername);

你的问题是callToPrint基本上声明它期望一个可以修改的C字符串,即不是const。因此使用LPTSTR代替LPTCSTR VC宏。它是否实际上改变了缓冲区取决于它的实现。现在,w_string.c_str()返回一个const wchar_t*,根据c_str()的定义,你不能改变它(即使你可以将它强制转换为wchar_t*,在这种情况下,你的代码将被编译)。

由于callToPrint是以这种方式声明的,因此必须为它提供一个非const C字符串。为此,您可以放弃使用wstring WprinterName,而使用wchar_t(或者TCHAR,如果您想坚持使用VC类型)的原始数组。在MultiByteToWideCharcallToPrint中使用这个缓冲区,不要忘记在最后释放它…

如果您确实需要wstring进行进一步处理,请阅读:Convert std::string to const char*或char*以获得一些额外的建议