linux 下 Linux 下char轉換為wchar_t

來源:互聯網
上載者:User

標籤:

LInux下使用mbstowcs函數可以將char轉化為wchar_t
函數含義:convert a multibyte string to a wide char string
說明:       The behaviour of mbstowcs depends on the LC_CTYPE category of the current locale
傳回值:   The  mbstowcs() function returns the number of wide characters that make up the converted part of the wide-char-acter string, not including the terminating null wide character.  If an invalid multibyte sequence  was  encountered, (size_t) -1 is returned.

 

 1 #include <string.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <wchar.h> 5 #include <locale.h> 6 #include <iostream> 7 using namespace std;10 // 將char類型轉化為wchar13 // locale: 環境變數的值,mbstowcs依賴此值來判斷src的編碼方式
11 int ToWchar(char* &src, wchar_t* &dest, const char *locale = "zh_CN.utf8"){18 if (src == NULL) {19 dest = NULL;20 return 0;21 }23 //根據環境變數設定locale24 setlocale(LC_CTYPE, locale);26 //得到轉化為需要的寬字元大小27 int w_size = mbstowcs(NULL, src, 0) + 1;29 //w_size=0說明mbstowcs傳回值為-1。即在運行過程中遇到了非法字元(很有可能使locale沒有設定正確)31 if (w_size == 0) {32 dest = NULL;33 return -1;34 }36 wcout << "w_size" << w_size << endl;37 dest = new wchar_t[w_size];38 if (!dest) return -1;42 int ret = mbstowcs(dest, src, strlen(src)+1);43 if (ret <= 0)return -1;46 return 0;47 }49 int main(){51 char* str = "中國123";52 wchar_t *w_str ;53 ToWchar(str,w_str);54 wcout << w_str[0] << "--" << w_str[1] << "--" << w_str[2];55 delete(w_str);56 return 0;57 }

 

 

 1 #include <stdio.h>   2    3 int main(void){   5        int       i_number, result;   6        float     f_number;   7        char      c_number, str[81];   8        wchar_t   wc_str, ws_str[81];  10        printf( "\n\nEnter an int, a float, two chars and two strings\n");  12        result = scanf( "%d %f %c %C %s %S", 
&i_number, &f_number, &c_number, &wc_str, str, ws_str ); 13 printf( "\nThe number of fields input is %d\n",
result ); 14 printf( "The contents are: %d %f %c %C %s %S\n",
i_number, f_number, c_number, wc_str, str, ws_str); 16 wprintf( L"\n\nEnter an int, a float, two chars and two strings\n"); 18 result = wscanf( L"%d %f %hc %lc %S %ls",
&i_number, &f_number, &c_number, &wc_str, str, ws_str ); 19 wprintf( L"\nThe number of fields input is %d\n",
result ); 20 wprintf( L"The contents are: %d %f %C %c %hs %s\n",
i_number, f_number, c_number, wc_str, str, ws_str); 21 }

 

linux 下 Linux 下char轉換為wchar_t

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.