wchar_t类型

有char、char[]、string;     有wchar_t、wchar_t []、wstring(这些用来存unicode字符,例如中文日文等)


法一:wcout.imbue(locale("chs"));(首选这个进行初始中文输出设置)

# include <iostream>
using namespace std;

int main()
{
    wcout.imbue(locale("chs"));    //设置wcout输出对象并输出中文字符

    wchar_t a = L'中';    //一个中文字符是单引号 L'中'    
    wcout << a << endl;;

    wchar_t b[12] = L"中国";    //多个中文字符是双引号 L"中国"
    wcout << b << endl;

    return 0;
}
法二: setlocale(LC_ALL, "chs");

# include <iostream>
using namespace std;
//wchar_t类型:输入保存中文字符与字符串-用法辨析范例;  PS:在Dev C++中由于编码器原因不能正确通过,需要在VS中实现完成 
int main()
{
	setlocale(LC_ALL, "chs");   //使用setlocale函数将本机的语言设置为中文简体,LC_ALL表示设置所有的选项,chs表示中文简体
	
        /* wchar_t有如下几种表达方式 */ 
//	wchar_t a;		//第一种:输入一个中文字符存入 a 
//	wcin>>a;   
//	wcout<<a<<endl;
//	
//	wchar_t a[12];	//第二种:输入一串中文字符串,[]中必须限定大小 
//	wcin>>a;     
//	wcout<<a<<endl;
	
	wchar_t a[] = L"中国你好!";	//第三种:输入一串中文字符串,[]不需要限定大小,但必须要加 L 
    wcout<<a<<endl;
    
    cout<<wcslen(a)<<endl;//wcslen输出宽字符串的长度,中国你好!输出长度是5  
    cout<<sizeof(a)<<endl;//输出长度是12个字节,最后的wchar_t类型的'\0'两个字节  
	
    return 0;
}

对于中文的字符串,统一在string模板里,以后就常用以下形式:

# include <iostream>
# include <string>
using namespace std;

int main()
{
	string str1("你好中国!");  //如果包装的是char数组,则字符串类型为string
	wstring str2(L"你好中国!");  //如果包装的是wchar_t数组,则字符串类型为wstring,记得加 L

       cout << str1 << endl;
	wcout.imbue(locale("chs"));  //设置输出为中文
	wcout << str2 << endl;

    return 0;
}
wchar_t 和 string类型之间的转换如下:

# include <iostream>
# include <string>
//string字符串到wchar_t的转换
using namespace std;
int main()
{
    setlocale(LC_ALL, "chs");
    
    string str ("你好中国");
    cout<<str<<endl;    //输出string的"你好中国"

    wchar_t * wc = new wchar_t[str.size()];
    swprintf(wc, 100, L"%S", str.c_str()); //string到wchar_t的转换。注意大写,wc指向的内存区域存储这wchar_t类型的"你好中国"
    wcout << wc<< endl;        //输出wchar_t的"你好中国"
    
    return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值