Since you didn't understand it, it would help if you could give us the code in which you're trying to convert from a WCHAR to a string so we can try to help you.
# include <windows.h>
# include <string>
int main()
{
WCHAR szBuffer[] = L"Convert this sz to string character";
std::string str;
str = szBuffer;/// Invalid conversion from WCHAR* to ...
return 0;
}
Sorry for the slow response was putting food in the oven.
Okay I see what you're trying to do.
I think this should suffice for the way you're approaching it.
Note: This approach assumes that the WCHAR array ends with a null terminator ('\0') which it will always end with if properly terminated which your array is in the way it is declared.
I developed the same function as WCHARtoString() ,also TCHAR to strings ,strings to TCHAR .. bref I found myself forced to develop function to handle convertions between datatypes ,and i thought maybe this is not a good way to do so
anyone knows good tuto about data types convertion
@ Pindrought
could you implement ,for me, a new function StringToWCHAR ? thanks
#include <windows.h>
#include <string>
#include <iostream>
std::string WCHARtoString(WCHAR wcharBuffer[])
{
std::string returnstring;
for (unsignedint i = 0; wcharBuffer[i] != '\0'; i++)
{
returnstring += wcharBuffer[i];
}
return returnstring;
}
WCHAR * StringToWCHAR(std::string strbuffer)
{
WCHAR * returnptr;
returnptr = new WCHAR[strbuffer.size()+1]; //We are allocating memory in this line and this is why we need to call delete when we're done with our WCHAR ptr
for (int i = 0; i < strbuffer.size(); i++)
{
returnptr[i] = strbuffer[i];
}
returnptr[strbuffer.size()] = '\0';
return returnptr;
}
int main()
{
WCHAR szBuffer[] = L"Convert this sz to string character";
std::string str;
str = WCHARtoString(szBuffer);
std::cout << "String Converted:" << str << std::endl;
WCHAR * strToWCharTest = StringToWCHAR(str);
std::wcout << "String Converted to WChar* :" << strToWCharTest << std::endl;
delete[] strToWCharTest; //Delete ptr to deallocate the memory that was allocated in the function
return 0;
}
For this you will be using a WCHAR * instead of a WCHAR array, but they perform exactly the same when used correctly.
Also, keep in mind to output to the stream, we have to use std::wcout instead of std::cout since we are outputting wide characters.
Also, since we are allocating memory in our stringtoWCHAR function, we have to call delete on our pointer after we are done using our WCHAR * so that we don't have memory leaks.
Hopefully it makes sense in my example where I delete the ptr after I am done using it.
No. We have to use the standard headers that came with the implementation. With different compilers, or different versions of a compiler, it is technically a different implementation of the standard library.
Most C++11 headers would not even compile without errors if we try to use them in legacy C++ mode.