1

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 ?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

2 Answers2

1

You also need to use .c_str() here.

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

getline(wcin, Wprintername);
Simon Richter
  • 28,572
  • 1
  • 42
  • 64
  • the line of error after using `WprinterName.c_str` says **error C2664: 'callToPrint' : cannot convert parameter 1 from 'const wchar_t *'to 'LPTSTR'** – Suhail Gupta Jul 14 '11 at 11:21
  • Can you fix your `callToPrint` function to accept constant strings? – Kerrek SB Jul 14 '11 at 11:24
  • And in that case, can you fix your `callToPrint` to accept a `std::wstring`? :-) – Bo Persson Jul 14 '11 at 11:29
  • @ Kerrek SB no..In tried casting `wchar*_t` to `LPTSTR` and it worked..How does that work ? – Suhail Gupta Jul 14 '11 at 11:29
  • @ Bo Persson what is the difference between `LPTSTR` and `wstring` ? If the first one is a pointer to wide string and the latter is a wide string then NO – Suhail Gupta Jul 14 '11 at 11:31
  • @Suhail - There are different kinds of strings, C style zero terminated arrays of characters, and C++ classes. `LPTSTR` is a macro that means either `wchar_t*` or `char*` depending on your project settings. With the right setting the cast works (because it doesn't do anything), with the other setting it does not work. – Bo Persson Jul 14 '11 at 11:47
0

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.

Community
  • 1
  • 1
Eran
  • 21,632
  • 6
  • 56
  • 89