linux下中文的wchar转char,Linux 下char转换为wchar_t
LInux下使用mbstowcs函數(shù)可以將char轉(zhuǎn)化為wchar_t
函數(shù)含義: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不要混合使用,否則會(huì)導(dǎo)致wchar_t的輸出問題
代碼:
#include
#include
#include
#include
#include
#include
using namespace std;
// 將char類型轉(zhuǎn)化為wchar
// src: 源
// dest: 目標(biāo)
// locale: 環(huán)境變量的值,mbstowcs依賴此值來判斷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 說明mbstowcs返回值為-1。即在運(yùn)行過程中遇到了非法字符(很有可能使locale
// 沒有設(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 = "中國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的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下collada-dom编译,
- 下一篇: linux at自动挂化,linux的a