Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why Return only First Character when Convert Cstring to LPCSTR

What I have tried:

Dear guy
I'm convert Cstring to LPCSTR with some code below

C++
CString strData1 = L"ABCDE";
LPCSTR spData = (LPCSTR)(LPCTSTR)strData1;
MessageBox(NULL, strData1, L"CString strData", MB_OK);      //=> ABCDE
MessageBox(NULL, (CString)spData, L"LPCSTR spData", MB_OK); //=> A  (What's problem)


Why LPCSTR spData is A (First Character of Cstring strData1)
Posted
Updated 14-Apr-23 3:47am
Comments
Mohibur Rashid 28-Jun-17 0:26am    
Casting and converting is not same.
take a look at this https://msdn.microsoft.com/en-us/library/s7wzt4be(v=vs.80).aspx

You cannot use a cast to convert data from one type to another; see WideCharToMultiByte function (Windows)[^]
 
Share this answer
 
As already said you need a conversion instead of a casting. The CString class can do that for you:
// Your code assumes a Unicode build and this example too

CString strData1 = L"ABCDE";

// Create a CStringA. 
// The conversion from Unicode to ANSI is done by the CString class.
// May also use CStringA strData1A(strData1);
CStringA strData1A = strData1;

// Get a LPCSTR from the CStringA
LPCSTR spData = strData1A.GetString();

MessageBox(NULL, strData1.GetString(), L"CString strData", MB_OK);

// Create a CString (CStringW) from a LPCSTR with conversion
MessageBox(NULL, CString(spData).GetString(), L"LPCSTR spData", MB_OK);

You should also avoid using C style castings. Use the C++ casting operators instead (see Type conversions - C++ Tutorials[^] and Casting Operators[^]).
 
Share this answer
 
Comments
Mạnh Lê 28-Jun-17 3:17am    
Thank you very much
CStringA strData1A(strData1)
one more thing , when you are using function check there should be a function for unicode also..

like in registry there is a function
RegCreateKeyExA
but for Unicode there is another version of same function called
RegCreateKeyExW



Mumtaz Ali
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900