Conversion between wchar_t char string wstring

Source: Internet
Author: User

Conversion between wchar_t, Char, string, and wstring is required when processing Chinese characters.

The conversion between char and string, wchar_t and wstring is relatively simple, and the code passes the test under vs2010.

# Include <iostream> # include <string> # include <tchar. h> # include <windows. h> using namespace STD; // converting a wchar string to a ANSI stringchar * W2C (char * pcstr, const wchar_t * pwstr, size_t Len) {int nlength = wcslen (pwstr ); // obtain the converted length int nbytes = widechartomultibyte (0, 0, pwstr, nlength, null, 0, null); If (nbytes> Len) nbytes = Len; // use the preceding result to convert Unicode characters to ASCII characters widechartomultibyte (, pwstr, nlength, pcstr, nbytes, null, null); Return pcstr;} int main () {setlocale (lc_all, "CHS"); char * Cc = "this is a char test"; wchar_t * WCC = l "This Is A wchar test "; string STR ("this is a string test"); wstring wstr = l "This Is A wstring test"; // string to charconst char * char_test = Str. c_str (); // cout <"char_test:" <char_test <Endl; // Char to stringstring Ss = cc; // cout <"SS is: "<SS <Endl; // wstring to wcharconst wchar_t * wchar_test = wstr. c_str (); // wcout <wchar_test <Endl; // wchar to wstringwstring WSS = WCC; wcout <WCC <Endl; // Char to wchar_twchar_t * WC = new wchar_t [Str. size () + 1]; // swprintf (WC, l "% s", CC); // wcout <CC <Endl; Delete [] WC; // wchar_t to charchar * pcstr = (char *) malloc (sizeof (char) * (2 * wcslen (WCC) + 1); memset (pcstr, 0, 2 * wcslen (WCC) + 1); W2C (pcstr, WCC, 2 * wcslen (WCC) + 1); free (pcstr); System ("pause "); return 1 ;}

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.