日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > linux >内容正文

linux

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

發(fā)布時(shí)間:2025/3/20 linux 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux下中文的wchar转char,Linux 下char转换为wchar_t 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

LInux下使用mbstowcs函數(shù)可以將char轉(zhuǎn)化為wchar_t

函數(shù)含義:convert a multibyte string to a wide char string

說(shuō)明: ? ? ??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不要混合使用,否則會(huì)導(dǎo)致wchar_t的輸出問(wèn)題

代碼:

#include

#include

#include

#include

#include

#include

using namespace std;

// 將char類(lèi)型轉(zhuǎn)化為wchar

// src: 源

// dest: 目標(biāo)

// locale: 環(huán)境變量的值,mbstowcs依賴(lài)此值來(lái)判斷src的編碼方式

// 運(yùn)行成功返回0 否則返回-1

//

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

{

if (src == NULL) {

dest = NULL;

return 0;

}

// 根據(jù)環(huán)境變量設(shè)置locale

setlocale(LC_CTYPE, locale);

// 得到轉(zhuǎn)化為需要的寬字符大小

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

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

// 沒(méi)有設(shè)置正確)

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 = "中國(guó)123";

wchar_t *w_str ;

ToWchar(str,w_str);

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

delete(w_str);

return 0;

}

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。