How to convert wstring into string?

前端 未结 17 2163
北海茫月
北海茫月 2020-11-22 13:10

The question is how to convert wstring to string?

I have next example :

#include 
#include 

int main()
{
    std::wstr         


        
17条回答
  •  [愿得一人]
    2020-11-22 13:32

    Here is a worked-out solution based on the other suggestions:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
      std::setlocale(LC_ALL, "");
      const std::wstring ws = L"ħëłlö";
      const std::locale locale("");
      typedef std::codecvt converter_type;
      const converter_type& converter = std::use_facet(locale);
      std::vector to(ws.length() * converter.max_length());
      std::mbstate_t state;
      const wchar_t* from_next;
      char* to_next;
      const converter_type::result result = converter.out(state, ws.data(), ws.data() + ws.length(), from_next, &to[0], &to[0] + to.size(), to_next);
      if (result == converter_type::ok or result == converter_type::noconv) {
        const std::string s(&to[0], to_next);
        std::cout <<"std::string =     "<

    This will usually work for Linux, but will create problems on Windows.

提交回复
热议问题