日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

linux下中文的wchar转char,Linux 下char转换为wchar_t

發布時間:2025/3/20 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux下中文的wchar转char,Linux 下char转换为wchar_t 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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.

注意:wcout 與cout不要混合使用,否則會導致wchar_t的輸出問題

代碼:

#include

#include

#include

#include

#include

#include

using namespace std;

// 將char類型轉化為wchar

// src: 源

// dest: 目標

// locale: 環境變量的值,mbstowcs依賴此值來判斷src的編碼方式

// 運行成功返回0 否則返回-1

//

int ToWchar(char* &src, wchar_t* &dest, const char *locale = "zh_CN.utf8")

{

if (src == NULL) {

dest = NULL;

return 0;

}

// 根據環境變量設置locale

setlocale(LC_CTYPE, locale);

// 得到轉化為需要的寬字符大小

int w_size = mbstowcs(NULL, src, 0) + 1;

// w_size = 0 說明mbstowcs返回值為-1。即在運行過程中遇到了非法字符(很有可能使locale

// 沒有設置正確)

if (w_size == 0) {

dest = NULL;

return -1;

}

wcout << "w_size" << w_size << endl;

dest = new wchar_t[w_size];

if (!dest) {

return -1;

}

int ret = mbstowcs(dest, src, strlen(src)+1);

if (ret <= 0) {

return -1;

}

return 0;

}

int main()

{

char* str = "中國123";

wchar_t *w_str ;

ToWchar(str,w_str);

wcout << w_str[0] << "--" << w_str[1] << "--" << w_str[2];

delete(w_str);

return 0;

}

總結

以上是生活随笔為你收集整理的linux下中文的wchar转char,Linux 下char转换为wchar_t的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。