How to convert wstring into string?

前端 未结 17 2164
北海茫月
北海茫月 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:16

    There are two issues with the code:

    1. The conversion in const std::string s( ws.begin(), ws.end() ); is not required to correctly map the wide characters to their narrow counterpart. Most likely, each wide character will just be typecast to char.
      The resolution to this problem is already given in the answer by kem and involves the narrow function of the locale's ctype facet.

    2. You are writing output to both std::cout and std::wcout in the same program. Both cout and wcout are associated with the same stream (stdout) and the results of using the same stream both as a byte-oriented stream (as cout does) and a wide-oriented stream (as wcout does) are not defined.
      The best option is to avoid mixing narrow and wide output to the same (underlying) stream. For stdout/cout/wcout, you can try switching the orientation of stdout when switching between wide and narrow output (or vice versa):

      #include 
      #include 
      #include 
      
      int main() {
          std::cout << "narrow" << std::endl;
          fwide(stdout, 1); // switch to wide
          std::wcout << L"wide" << std::endl;
          fwide(stdout, -1); // switch to narrow
          std::cout << "narrow" << std::endl;
          fwide(stdout, 1); // switch to wide
          std::wcout << L"wide" << std::endl;
      }
      

提交回复
热议问题