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.
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!
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!
std::setlocale()
.std::string
is compatible with the conversion process.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.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ObjectsA practical guide covering the most useful methods and operators for working with std::string
objects and their memory