wchar 跟 char 之間轉換

來源:互聯網
上載者:User

源頭是百度部落格一大仙兒的,經過自己幾次改進,應該沒有問題了

#include<iostream>#include <stdlib.h>#include <stdio.h>#include <string.h>using namespace std;size_t get_wchar_size(const char *str){size_t len = strlen(str);size_t size=0;size_t i;for(i=0; i < len; i++){if( str[i] >= 0 ) //不是全形字元size+=sizeof(wchar_t);else //是全形字元,是中文{size+=sizeof(wchar_t);i+=1;}}return size;}char *w2c(const wchar_t *pw){if(!pw)return NULL;size_t size= wcslen(pw)*sizeof(wchar_t) + sizeof(char);char *pc;if(!(pc = (char*)malloc(size))){printf("malloc fail");return NULL;}memset(pc, 0, size);wcstombs(pc,pw,size);return pc;}wchar_t *c2w(const char *pc){if(!pc)return NULL;size_t size_of_ch = strlen(pc)*sizeof(char);size_t size_of_wc = get_wchar_size(pc) + sizeof(wchar_t);wchar_t *pw;if(!(pw = (wchar_t*)malloc(size_of_wc))){printf("malloc fail");return NULL;}memset(pw, 0, size_of_wc);mbstowcs(pw,pc,size_of_wc);return pw;}int main(void){setlocale(LC_ALL,"zh_CN.utf8");printf("1 print chinese by wprintf test: \n");wchar_t *wstr = L"中文";//wprintf(L"%ls",wstr);printf("%ls\n",wstr); //lsprintf("2 print chinese by printf test: \n");char *str = "漢字";printf("%s\n\n\n",str); //sprintf("3 char and wchar_t size of system test: \n");printf("%s%d\n","the size of wchar_t is : ",sizeof(wchar_t)); //4printf("%s%d\n\n\n","the size of char is : ",sizeof(char));   //1char *pc;wchar_t *pw = L"中文是abc一門語言abc";char *tmp = "中文是abc一門語言abc";printf("%s%s\n","input test wchar_t* ",tmp);pc = w2c(pw);printf("4 print char test after w2c (wchar to char):\n");printf("%s\n",pc);wchar_t *cw1 = c2w(pc);   //char to wcharchar *wc1 = w2c(cw1);   //wchar to charprintf("5 print char test after w2c c2w and w2c:\n");printf("%s\n\n\n",wc1);char *pmc = "abc中文abc";wchar_t *pmw;printf("%s%s\n","input test char* ",pmc);pmw = c2w(pmc);char *pmc1 = w2c(pmw);printf("6 print char test after c2w and w2c:\n");printf("%s\n",pmc1);free(pc);                 free(cw1);free(wc1);return 0;}

源貼:  http://hi.baidu.com/yangyangye2008/blog/item/fcb0943115fc7294a8018e15.html#0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.