宽窄字符系列

1:日志打印

windows下我们需要测试某些数据的正确性,比较难以单独获取数据的时候,日志是个比较好的办法

#include <iostream>
#include <Windows.h>
#include <tchar.h>
using namespace std;

void DbgPrint(const TCHAR *format, ...)//宽字节
{
	TCHAR buf[4096];
	va_list args;
	va_start(args, format);
	_vstprintf(buf,format, args);
	va_end(args);
	OutputDebugString(buf);
}
void DbgPrint(const char *format, ...)//窄字节
{  
	char buf[4096];  
	va_list args;  
	va_start(args, format);  
	_vsnprintf(buf, sizeof(buf) - 1, format, args);  
	va_end(args);  
	OutputDebugStringA(buf);  
}

int main()
{
	DbgPrint("nihao %s %d","lili",90);
	DbgPrint(_T("nihao %s %d"),_T("lili"),90);
	return 0;
}

结果:


2:宽字符和窄字符的转换

	//将窄字符转化为宽字符(双字符,此时字符都占用两个字节,不再是一个字节)
	char c_str[256]="nihao";
	int num_c = MultiByteToWideChar(0,0,c_str,-1,NULL,0);
	wchar_t *wc_str = new wchar_t[num_c];
	MultiByteToWideChar(0,0,c_str,-1,wc_str,num_c);
	wcout<<wc_str<<endl;

	//将宽字符转化为窄字符
	TCHAR szBuf[256]=_T("nihao");
	int num_wc=WideCharToMultiByte(CP_OEMCP,NULL,szBuf,-1,NULL,0,NULL,FALSE);
	char *c_name=new char[num_wc+1];
	WideCharToMultiByte(CP_OEMCP,NULL,szBuf,-1,c_name,num_wc,NULL,FALSE);
	c_name[num_wc]=0;
	cout<<c_name<<endl;

3:求宽窄字符串的长度

	char t1[123];
	TCHAR t2[31];
	cout << _countof(t2)<<endl;
	cout << sizeof(*__countof_helper(t2))<<endl;


	TCHAR *t3 = new TCHAR[10];
	cout<<"777:"<<_tcslen(t3)<<endl;
	cout<<"777:"<<wcslen(t3)<<endl;












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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值