Convert to wstring
How can I convert a std::string to a std::wstring?
Converting a std::string to a std::wstring involves converting between narrow (char) and wide (wchar_t) characters. This is often necessary when dealing with different character encodings, such as ASCII and Unicode.
Basic Conversion
To convert a std::string to a std::wstring, you need to handle the conversion of each character. The simplest way to do this is to use the std::wstring constructor that takes a std::string as an argument. For example:
#include <iostream>
#include <string>
int main() {
std::string NarrowString{"Hello, World!"};
std::wstring WideString{
NarrowString.begin(), NarrowString.end()
};
std::wcout << WideString;
}Hello, World!Using std::mbstowcs
For more control over the conversion, especially with different locales, you can use std::mbstowcs which stands for multi-byte string to wide-character string. For example:
#include <iostream>
#include <string>
#include <cwchar>
#include <vector>
int main() {
std::string NarrowString{"Hello, World!"};
std::vector<wchar_t> WideString(
NarrowString.size() + 1
);
size_t convertedChars = 0;
#ifdef _WIN32
mbstowcs_s(
&convertedChars, &WideString[0],
WideString.size(), NarrowString.c_str(),
NarrowString.size()
);
#else
convertedChars = mbstowcs(
&WideString[0],
NarrowString.c_str(),
WideString.size()
);
#endif
std::wcout << &WideString[0];
}Hello, World!Considerations
- Locale: The conversion depends on the current C locale. You can set the locale using
std::setlocale(). - Encoding: Ensure that the encoding of the
std::stringis compatible with the conversion process.
Advanced Conversion
For more complex scenarios, such as converting between different character sets, consider using libraries like ICU (International Components for Unicode) or Boost.Locale.
#include <boost/locale.hpp>
#include <iostream>
#include <string>
int main() {
std::string NarrowString{"Hello, World!"};
std::wstring WideString =
boost::locale::conv::to_utf<wchar_t>(
NarrowString, "UTF-8"
);
std::wcout << WideString;
}Hello, World!Converting between std::string and std::wstring allows you to handle different text encodings, making your applications more versatile in handling international text.
Manipulating std::string Objects
A practical guide covering the most useful methods and operators for working with std::string objects and their memory