wchar_t char string wstring 之间的转换

本文介绍了一种在C++中实现wchar_t、char、string和wstring之间相互转换的方法,并提供了一个具体的示例代码,展示了如何使用Windows API进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在处理中文时有时需要进行wchar_t,char,string,wstring之间的转换。

其中char和string之间、wchar_t和wstring之间的转换较为简单,代码在vs2010下测试通过。

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3. #include <tchar.h>  
  4. #include <Windows.h>  
  5.   
  6. using namespace std;  
  7.   
  8. //Converting a WChar string to a Ansi string  
  9. char *w2c(char *pcstr,const wchar_t *pwstr, size_t len)  
  10. {  
  11.     int nlength=wcslen(pwstr);  
  12.     //获取转换后的长度  
  13.     int nbytes = WideCharToMultiByte( 0, 0, pwstr, nlength, NULL,0,NULL, NULL );   
  14.     if(nbytes>len)   nbytes=len;  
  15.     // 通过以上得到的结果,转换unicode 字符为ascii 字符  
  16.     WideCharToMultiByte( 0,0, pwstr, nlength,   pcstr, nbytes, NULL,   NULL );  
  17.     return pcstr ;  
  18. }  
  19.   
  20. int main(){  
  21.   
  22.     setlocale(LC_ALL,"chs");  
  23.     char* cc = "this is a char 测试";  
  24.     wchar_t* wcc = L"this is a wchar 测试";  
  25.     string str("this is a string 测试 ");  
  26.     wstring wstr = L"this is a wstring 测试";  
  27.   
  28.   
  29.     //string to char  
  30.     const char* char_test = str.c_str();   
  31.     //cout<<"char_test:"<<char_test<<endl;  
  32.   
  33.     //char to string  
  34.     string ss = cc;  
  35.     //cout<<"ss is :"<<ss<<endl;  
  36.   
  37.     //wstring to wchar  
  38.     const wchar_t* wchar_test = wstr.c_str();   
  39.     //wcout<<wchar_test<<endl;  
  40.   
  41.     //wchar to wstring  
  42.     wstring wss = wcc;  
  43.     wcout<<wcc<<endl;  
  44.   
  45.     //char to wchar_t  
  46.     wchar_t *wc = new wchar_t[str.size()+1];  
  47.     //swprintf(wc,L"%S",cc);   
  48.     //wcout<<cc<<endl;  
  49.     delete []wc;  
  50.       
  51.     // wchar_t to char  
  52.     char *pcstr = (char *)malloc(sizeof(char)*(2 * wcslen(wcc)+1));  
  53.     memset(pcstr , 0 , 2 * wcslen(wcc)+1 );  
  54.     w2c(pcstr,wcc,2 * wcslen(wcc)+1) ;  
  55.     free(pcstr);  
  56.       
  57.     system("pause");  
  58.     return 1;  
  59. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值