Suhail Gupta
Suhail Gupta

Reputation: 23276

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

I converted a narrow string to the wide string as follows :

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'

Why is it so ? and please tell me how can i fix it ?

Upvotes: 1

Views: 1463

Answers (2)

Eran
Eran

Reputation: 22020

Your problem is that callToPrint basically states it expects a C string it can modify, i.e. not const. Hence the use if LPTSTR instead of LPTCSTR VC macro. Whether it in fact changes the buffer or not depends on its implementation. Now, w_string.c_str() returns a const wchar_t*, which according to the definition of c_str() you must not change (even if you can cast it to a wchar_t*, in which case your code will compile.

Since callToPrint is declared that way, you must provide it with a non-const C string. For that, you can drop the use of wstring WprinterName, and use a raw array of wchar_t (or TCHAR, if you want to stick to VC types). Use that buffer in MultiByteToWideChar and callToPrint, and don't forget to free it at the end...

If you do need the wstring for further processing, read: Convert std::string to const char* or char* for some additional suggestions.

Upvotes: 0

Simon Richter
Simon Richter

Reputation: 29618

You also need to use .c_str() here.

Also, I'd read the printer name directly into WprinterName, using

getline(wcin, Wprintername);

Upvotes: 1

Related Questions