Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print u32string and u16string to the console in c++

Tags:

c++

string

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??

like image 728
mitesh Avatar asked Aug 25 '17 05:08

mitesh


1 Answers

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.

like image 97
Bur Avatar answered Sep 20 '22 14:09

Bur