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

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

2 #include

3 #include

4 #include

5 #include

6 #include

7 using namespacestd;

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 //根据环境变量设置locale

24 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 <

42 int ret = mbstowcs(dest, src, strlen(src)+1);43 if (ret <= 0)return -1;46 return 0;47 }

49 intmain(){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

2

3 int main(void){5 inti_number, result;6 floatf_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 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值