Wchar_t char string wstring conversion

  • 2020-04-02 01:42:14
  • OfStack

Sometimes wchar_t, char, string, wstring conversion is required when dealing with Chinese.

Among them, the conversion between char and string, wchar_t and wstring is relatively simple, and the code passed the test under vs2010.


#include <iostream>
#include <string>
#include <tchar.h>
#include <Windows.h>
using namespace std;
//Converting a WChar string to a Ansi string
char *w2c(char *pcstr,const wchar_t *pwstr, size_t len)
{
 int nlength=wcslen(pwstr);
 //Gets the converted length
 int nbytes = WideCharToMultiByte( 0, 0, pwstr, nlength, NULL,0,NULL, NULL ); 
 if(nbytes>len)   nbytes=len;
 //With the results obtained above, convert unicode characters to ASCII characters
 WideCharToMultiByte( 0,0, 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 char
 const char* char_test = str.c_str(); 
 //cout<<"char_test:"<<char_test<<endl;
 //char to string
 string ss = cc;
 //cout<<"ss is :"<<ss<<endl;
 //wstring to wchar
 const wchar_t* wchar_test = wstr.c_str(); 
 //wcout<<wchar_test<<endl;
 //wchar to wstring
 wstring wss = wcc;
 wcout<<wcc<<endl;
 //char to wchar_t
 wchar_t *wc = new wchar_t[str.size()+1];
 //swprintf(wc,L"%S",cc); 
 //wcout<<cc<<endl;
 delete []wc;

 // wchar_t to char
 char *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;
}


Related articles: