Answer the question
In order to leave comments, you need to log in
How to correctly convert wchar_t type to string?
I am writing applications on Visual Studio 2017 (console) in which I need to convert the wchar_t type to string, I came to such a solution, here is part of the code:
WCHAR buffer[2048];
int main()
{
setlocale(LC_ALL, "Rus");
string path;
GetModuleFileName(NULL, buffer, sizeof(buffer) / sizeof(buffer[0]));
for (int i = 0; i < (sizeof(buffer) / sizeof(buffer[0])); i++) {
path += buffer[i];
}
Answer the question
In order to leave comments, you need to log in
The type WCHAR
depends on the project settings and can be either an alias char
or a wchar_t
. Widespread use of this type throughout the project is not recommended. introduces uncertainty everywhere.
To store Unicode strings (you have 2017 studio and c++17 by default), there have long been several types of strings at once : std::wstring
, std::u16string
and std::u32string
.
The type std::wstring
stores characters of type wchar_t
, which, depending on compiler settings, can take 2 or 4 bytes. This makes the type std::wstring
as ambiguous as WCHAR
. Therefore, types with a strict character size were created: std::u16string
and std::u32string
. Now it is recommended to use them together with std::string
.
Your question itself is not about type conversion, because this is easily done with a std::transform
lambda, but in converting a single-byte (std::string) encoding to Unicode and vice versa.
For this, the standard library also already has everything you need .
template< typename TCharType, typename TCharTraits, typename TStringAllocator >
inline void Convert( const std::string& source_string, std::basic_string<TCharType, TCharTraits, TStringAllocator>& dest_string )
{
std::wstring_convert<std::codecvt_utf8_utf16<TCharType>, TCharType> converter;
dest_string = converter.from_bytes( source_string );
}
template< typename TCharType, typename TCharTraits, typename TStringAllocator >
inline void Convert( const std::basic_string<TCharType, TCharTraits, TStringAllocator>& source_string, std::string& dest_string )
{
std::wstring_convert<std::codecvt_utf8_utf16<TCharType>, TCharType> converter;
dest_string = converter.to_bytes( source_string );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question