Conversion between char * And wchar_t *

Source: Internet
Author: User
Most of the conversions between char * And wchar_t * in C ++ are tedious and not feasible. The following method is found in msdn. I think it is quite good:

 

SetChar *ConvertWchar_t *

Using the mbstowcs_s function in stdlib. H, you can use the following example to understand its usage:

 

Char * CSTR = "string to convert ";

Size_t Len = strlen (CSTR) + 1;

Size_t converted = 0;

Wchar_t * wstr;

Wstr = (wchar_t *) malloc (LEN * sizeof (wchar_t ));

Mbstowcs_s (& converted, wstr, Len, CSTR, _ truncate );

 

The result is that the wchar_t version of CSTR is stored in wstr.

 

SetWchar_t *ConvertChar *

Similar to the preceding method, use the wcstombs_s function in stdlib. H. For example:

 

Wchar_t * wstr = l "string to convert ";

Size_t Len = wcslen (wstr) + 1;

Size_t converted = 0;

Char * CSTR;

CSTR = (char *) malloc (LEN * sizeof (char ));

Wcstombs_s (& converted, CSTR, Len, wstr, _ truncate );

 

In this case, the content in wstr will be converted to Char and stored in CSTR.

 

In addition, you can use the stream method to convert the char * type to the wchar_t * type, but the conversion result will be the const type, similar methods cannot convert the wchar_t * type to the char * type.

 

Put (Const)Char *ConvertConst wchar_t *

You need to use the sstream header file:

 

Char * CSTR = "string to convert ";

Wstringstream WSS;

WSS <CSTR;

 

Call WSS. STR (). c_str (); to obtain the return value of the const wchar_t * type.

 

Although the stringstream stream cannot convert wchar_t * To char *, it can be used to convert the value type and string. For example:

 

Double D = 2734792.934f;

Stringstream SS;

SS <D;

 

Call ss. STR () to obtain the string type string "273479e + 006", as shown in the following figure:

 

String STR ("299792458 ");

Stringstream SS;

Long I = 0;

SS <STR;

SS> I;

At this time, I = 299792458.

 

From: http://blog.163.com/tianshi_17th/blog/static/4856418920085209414977/

 

 

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.