如何在C++中将u32string和u16string打印到控制台

18

我最近遇到了字符串文字,并发现了一些新的字符串类型,比如u16string和u32string。我发现可以使用std::wcout将wstring打印到控制台,但对于u16string或u32string则不起作用。如何将它们打印到控制台?


2
请查看此链接 ---------------------> https://dev59.com/VHLYa4cB1Zd3GeqPUzMK#16594382 - N1gthm4r3
2
©N1gthm4r3 codecvt在C++17中已被弃用。 - n. m.
2个回答

7

我猜下面的代码应该可以工作,但请注意,在c++17中<codecvt>已被弃用。

#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;
}

也许这样也可以行得通,
#include <string>
#include <iostream>

int main() {
  std::u16string str(u"abcdefg");
  for (const auto& c: str)
    std::cout << static_cast<char>(c);
}

不确定后者的稳健性以及您需要它有多高的效率。


1

@Burgers的解决方案适用于clang 12.0.0(macOS Catalina XCode)。

请注意,对于u32string,您需要使用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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接