Reputation: 347
I recently bumped into string literals and found some new strings like u16string and u32string. I found that wstring can be printed to the console using std::wcout, but that doesn't work for u16string or u32string. How can i print these to the Console??
Upvotes: 18
Views: 10994
Reputation: 12524
@Burgers' solution works in clang 12.0.0 (macOS Catalina XCode)
Note that for u32string you need to use char32_t.
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main() {
using namespace std;
u32string str = u"εΎζη¨π"; // btw. str.size() == 4
wstring_convert<codecvt_utf8<char32_t>, char32_t> converter;
cout << converter.to_bytes(str) << endl;
return 0;
}
Upvotes: 1
Reputation: 157
I guess the below code would work, but note that <codecvt>
is deprecated in c++17.
#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
int main() {
std::u16string str = u"sample";
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
std::cout << converter.to_bytes(str) << std::endl;
return 0;
}
Maybe something like this could work as well,
#include <string>
#include <iostream>
int main() {
std::u16string str(u"abcdefg");
for (const auto& c: str)
std::cout << static_cast<char>(c);
}
Not sure how robust the latter is, and how efficient you need it to be.
Upvotes: 7