我持有无符号整数size_t的十六进制值,并希望将它们转换为wchar_t以保存在数据结构中,并且可以选择在有效时打印到std::cout作为UTF-8符号/字符。
我试过铸造,但没有成功:size_t h = 0x262E;在对9774进行铸造时打印wchar_t
一些最小的代码:

#include <iostream>
#include <vector>

int main() {
   std::setlocale( LC_ALL, "" );
   auto v = std::vector<size_t>( 3, 0x262E ); // 3x peace symbols
   v.at( 1 ) += 0x10; // now a moon symbol

   for( auto &el : v )
       std::cout << el << " ";

    return 0;
}

输出:9774 9790 9774
我想要的:☮ ☾ ☮
我可以使用printf( "%lc ", (wchar_t) el );打印符号。有更好的“现代”C++解决方案吗?
我只需要在linux上打印0000-27BFUTF-8范围内的任何内容。

最佳答案

您需要std::wcoutwchar_t转换来打印宽字符,而不是std::cout
这是您正确的功能代码(live example):

#include <iostream>
#include <vector>

int main() {
   std::setlocale( LC_ALL, "" );
   auto v = std::vector<size_t>( 3, 0x262E ); // 3x peace symbols
   v.at( 1 ) += 0x10; // now a moon symbol

   for( auto &el : v )
       std::wcout << (wchar_t) el << " "; // <--- Corrected statement

    return 0;
}

输出:
☮ ☾ ☮

如果您有十六进制字符串编号,可以遵循this解决方案。

关于c++ - 十六进制值到wchar_t字符(UTF-8)的转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53154257/

10-11 03:26
查看更多