15

I have a CString variable that i a need to convert to LPCTSTR(const char*) .I need this conversion so that i can use it as an argument in a function .

The CString look like :

CString sqlTemp = _T("INSERT INTO "+ sw1 +" (filename, "+ sw2 +") VALUE ("+ sw7 +","+ sw3 +" ) ");

It contains an query. The prototype of the function is :

int WriteBlob(LPCTSTR szSqlStat, LPCTSTR szFilePath)

So could you show me an exemple of how to convert to LPCTSTR ? It may be trivial but i am a c++ beginner and i still get a hang of it.

Thanks .

Ionut Daniel
  • 312
  • 2
  • 9
  • 20

2 Answers2

17

One method of conversion is like this:

CString str;

str = "Hello";

LPCSTR szTemp = (LPCSTR)(LPCTSTR)str;
Ionut Hulub
  • 6,180
  • 5
  • 26
  • 55
  • 3
    Can you also explain as to why there are so many different formats (LPCTSTR, CString, char*, string, etc...) which are all basically the same? Or is there some difference I just cannot see? – SinisterMJ Sep 27 '12 at 12:17
  • 5
    fell string is an object so you can call methods on it unlike all the others. char* is basically an array of chars. Cstring is also an array of chars but they can take 2 bytes depending on the encoding. LPCTSTR is a pointer to a constant string, so you can't modify it. – Ionut Hulub Sep 27 '12 at 12:20
  • 3
    " Cstring is also an array of chars" no, it's not. – Tamás Szelei Apr 15 '14 at 11:51
  • @TamásSzelei It does point at an LPSTR / LPWSTR though. – Ray Aug 01 '20 at 15:24
0
CString str; // the given string
CStringA strA(str); // a helper string
LPCSTR ptr = strA;

Reference MSDN

JD-V
  • 3,336
  • 1
  • 17
  • 20