Conversion of Char and WCHAR in STL

Source: Internet
Author: User

Learning Record:

In STL, the string str naturally corresponds to a string

The wide string wchar corresponds to the wstring

A wide string occupies two bytes

There are three ways to convert the two

1 Windows API conversion function WideCharToMultiByte () with MultiByteToWideChar (). Not suitable for cross-platform use.

2 ATL in ca2w class and CW2A class. Or use the A2W macro with the W2A macro. A little cumbersome and troublesome

3 Use the CRT library functions and methods of use see the following code

#include <string>#include<iostream>#include<locale.h>using namespacestd;stringWs2s (ConstWstring &ws) {    Constwchar_t* Wpchar =Ws.c_str (); size_t ReturnVal=0; size_t wsize=2*ws.size () +1; Char* Pchar =New Char[wsize]; memset (Pchar,0, wsize); wcstombs_s (&returnval,pchar,wsize,wpchar,wsize); stringresult =Pchar;    Delete[] Pchar; returnresult;}int_tmain (intARGC, _tchar*argv[]) {setlocale (Lc_all,"CHS"); wstring ws= L"China Hello, SF*&%*&^%^&SD, this is a test"; stringSS =ws2s (WS); Wcout<< ws <<Endl; cout<< SS <<Endl; return 0;}

Conversion of Char and WCHAR in STL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.