How do I convert wchar_t* to std::string?

前端 未结 6 1520
孤独总比滥情好
孤独总比滥情好 2020-12-09 08:16

I changed my class to use std::string (based on the answer I got here but a function I have returns wchar_t *. How do I convert it to std::string?

I tried this:

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 08:28

    You can convert a wide char string to an ASCII string using the following function:

    #include 
    #include 
    #include 
    
    std::string ToNarrow( const wchar_t *s, char dfault = '?', 
                          const std::locale& loc = std::locale() )
    {
      std::ostringstream stm;
    
      while( *s != L'\0' ) {
        stm << std::use_facet< std::ctype >( loc ).narrow( *s++, dfault );
      }
      return stm.str();
    }
    

    Be aware that this will just replace any wide character for which an equivalent ASCII character doesn't exist with the dfault parameter; it doesn't convert from UTF-16 to UTF-8. If you want to convert to UTF-8 use a library such as ICU.

提交回复
热议问题