c, c ++ char * and interchangeable wchar *

1. Description of the problem
  will usually face some different encoding formats, such as Unicode and multibytes write programs. Particularly important when dealing with strings, often encounter many such problems when the system is programmed, for example, to convert a string wchar * char * string, sometimes also need to type char * string into wchar *Types of. We offer several solutions below.

2. Solution
2.1 wchar * to char *
  method, using _bstr_t conversion.
  

#include <comdef.h> Will you need the this //
const WCHAR * WC = L "the Hello World";
_bstr_t B (WC);
const char * B = C;
the printf ( "the Output:% S \ n-", C) ;

  Second method, using conversion macros.
  Contained in the header file #include <atlconv.h>, the need to be cautious! Because the space transformer string allocated on the stack, is not released until the function returns. Such as the return to use many times, for example, using a recursive function, the easily lead to memory overflow.

USES_CONVERSION;
WCHAR * WC = L "the Hello World";
char * C = W2A (WC);

  Three methods used sprintf, relatively simple.
  

Output char [256];
WCHAR * WC = L "Hellow World";
sprintf (Output, "% WS", WC);

2.2 revolutions wchar * char *
  method: used mbstowcs function.
  

const wchar_t *GetWC(const char *c)
{
const size_t cSize = strlen(c)+1;
wchar_t* wc = new wchar_t[cSize];
mbstowcs (wc, c, cSize);

WC return;
}

  two: USES_CONVERSION.
  Usage and precautions above.
  

USES_CONVERSION;
char * C = L "the Hello World";
Wchar A2W * WC = (C);

  Method 3: Use swprintf functions, recommended.
  

WS wchar_t [100];
of swprintf (WS, 100, L "% HS", "ANSI String");
---------------------
Copyright: This is CSDN bloggers "jeanphorn 'original article, follow the CC 4.0 by-sa copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/Jeanphorn/article/details/45745739

Guess you like

Origin www.cnblogs.com/qiumingcheng/p/11334930.html