殷德好

C++中宽字符类型的定义及使用

1. 宽字符类型的定义
    宽字符类型 wchar_t 是这样来的:

typedef short int wchar_t;

    所以 wchar_t 实际上的空间是和 short int 一样,占两个字节。
    宽字符类型wchar_t常用来存储中文、日文和韩文;
    使用前需包含头文件,并声明语言区域:

#include<locale>
setlocale(LC_ALL, "chs");//指定字符区域为中文

 2. 下面给出在VS2010,win32环境下宽字符类型和单字符类型的比较

#include<iostream>
#include<locale>
using namespace std;
int main()
{
 setlocale(LC_ALL, "chs");//指定字符区域为中文
 wchar_t st[] = L"中文的";
 char stc[] = "中文的";
 wcout<<st<<endl;//宽字符类型数组的内容:"中文的"
 cout<<stc<<endl;//单字符类型的内容:"中文的"
 cout<<st<<endl;//宽字符类型数组的地址
 cout<<&stc<<endl;//单字符类型的地址
 cout<<sizeof(st)<<endl;//宽字符类型数组的大小:3*2+2 = 8;
 cout<<sizeof(stc)<<endl;//单字符类型数组的大小:6*1+1 = 7;中文字符以两个单字符存储
 cout<<"------------------------------"<<endl;
 cout<<sizeof(char)<<endl;
 cout<<sizeof(wchar_t)<<endl;
 return 0;
 }

posted on 2020-01-29 15:44  殷德好  阅读(4563)  评论(0编辑  收藏  举报

导航