Why doesn't printf format unicode parameters?

前端 未结 2 2030
[愿得一人]
[愿得一人] 2020-12-09 21:33

When using printf to format a double-byte string into a single-byte string:

printf(\"%ls\\n\", L\"s:\\\\яшертыHello\");   // %ls for a wide string (%s varies         


        
2条回答
  •  误落风尘
    2020-12-09 22:00

    In C++ I usually use std::stringstream to create formatted text. I also implemented an own operator to use Windows function to make the encoding:

    ostream & operator << ( ostream &os, const wchar_t * str )
    {
      if ( ( str == 0 ) || ( str[0] == L'\0' ) )
       return os;
      int new_size = WideCharToMultiByte( CP_UTF8, 0, str, -1, NULL, NULL, NULL, NULL );
      if ( new_size <= 0 )
        return os;
      std::vector buffer(new_size);
      if ( WideCharToMultiByte( CP_UTF8, 0, str, -1, &buffer[0], new_size, NULL, NULL ) > 0 )
        os << &buffer[0];
      return os;
    }
    

    This code convert to UTF-8. For other possibilities check: WideCharToMultiByte.

提交回复
热议问题