How to convert wstring into string?

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

    Solution from: http://forums.devshed.com/c-programming-42/wstring-to-string-444006.html

    std::wstring wide( L"Wide" ); 
    std::string str( wide.begin(), wide.end() );
    
    // Will print no problemo!
    std::cout << str << std::endl;
    

    Beware that there is no character set conversion going on here at all. What this does is simply to assign each iterated wchar_t to a char - a truncating conversion. It uses the std::string c'tor:

    template< class InputIt >
    basic_string( InputIt first, InputIt last,
                  const Allocator& alloc = Allocator() );
    

    As stated in comments:

    values 0-127 are identical in virtually every encoding, so truncating values that are all less than 127 results in the same text. Put in a chinese character and you'll see the failure.

    -

    the values 128-255 of windows codepage 1252 (the Windows English default) and the values 128-255 of unicode are mostly the same, so if that's teh codepage you're using most of those characters should be truncated to the correct values. (I totally expected á and õ to work, I know our code at work relies on this for é, which I will soon fix)

    And note that code points in the range 0x80 - 0x9F in Win1252 will not work. This includes , œ, ž, Ÿ, ...

提交回复
热议问题