您的位置:首页 > 运维架构 > Linux

linux 下 Linux 下char转换为wchar_t 设置本地为utf-8编码 以及wchar 的输入输出

2015-05-29 16:47 441 查看
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.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>
#include <iostream>
using namespace std;
// 将char类型转化为wchar // locale: 环境变量的值,mbstowcs依赖此值来判断src的编码方式
11 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;
}


#include <stdio.h>

int main(void){
int       i_number, result;
float     f_number;
char      c_number, str[81];
wchar_t   wc_str, ws_str[81];
printf( "\n\nEnter an int, a float, two chars and two strings\n");
result = scanf( "%d %f %c %C %s %S",
&i_number, &f_number, &c_number, &wc_str, str, ws_str );
printf( "\nThe number of fields input is %d\n",
result );
printf( "The contents are: %d %f %c %C %s %S\n",
i_number, f_number, c_number, wc_str, str, ws_str);
wprintf( L"\n\nEnter an int, a float, two chars and two strings\n");
result = wscanf( L"%d %f %hc %lc %S %ls",
&i_number, &f_number, &c_number, &wc_str, str, ws_str );
wprintf( L"\nThe number of fields input is %d\n",
result );
wprintf( L"The contents are: %d %f %C %c %hs %s\n",
i_number, f_number, c_number, wc_str, str, ws_str);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: