在做字符串、文本操作時,我們時常會需要在wchar_t *和char *之間做轉換或搭橋。直 接用API,參數太多不容易記住,常常要查文檔,浪費不少時間。為了自己方便,對簡單的轉 換寫了一個簡單的轉換包裝類。下次或者用得著,帖代碼做為保存。
順便提一下:發現有個東西很好用,std::stringstream系列 (#include < sstream >);其實,流式操作用起來都很happy,還有iostream、fstream;還有TCP的數據也是流 式的。
頭文件:string.h
#pragma once
#ifndef __STRING__
#define __STRING__
/**
* 以下代碼由張家旺編寫完成於2007-12-5,借用請保留該聲明。
*/
namespace useful
{
class translator
{
public:
static wchar_t *translate(
const char *str,size_t sub,wchar_t buf[],size_t num );
static char *translate(
const wchar_t *str,size_t sub,char buf[],size_t num );
const wchar_t *translate( const char *str,size_t sub = -1 );
const char *translate( const wchar_t *str,size_t sub = -1 );
translator( void );
~translator( void );
static translator &instance( void );
private:
void buffer( size_t len )
{
if( len > m_len )
{
delete[] m_buf;
m_buf = new char[len];
m_len = len;
}
}
char *m_buf;
size_t m_len;
};
};
#endif //__STRING__
實現文件:string.cpp
#include < string >
#include < windows.h >
#include "./string.h"
#pragma warning( disable : 4267 )
namespace useful
{
translator::translator( void ) : m_buf( 0 ),m_len( 0 )
{
}
translator::~translator( void )
{
delete[] m_buf;
}
translator &translator::instance( void )
{
static translator impl = translator();
return impl;
}
wchar_t *translator::translate(
const char *str,size_t sub,wchar_t buf[],size_t num )
{
::MultiByteToWideChar( CP_OEMCP,0,str,sub,buf,num );
return buf;
}
char *translator::translate(
const wchar_t *str,size_t sub,char buf[],size_t num )
{
::WideCharToMultiByte( CP_OEMCP,0,str,sub,buf,num,0,0 );
return buf;
}
const wchar_t *translator::translate( const char *str,size_t sub )
{
if( sub == std::string::npos ) sub = strlen( str );
buffer( (sub+1) * 2 );
wchar_t *buf = reinterpret_cast< wchar_t * >( m_buf );
buf[sub] = L'\0';
return translate( str,sub,buf,sub );
}
const char *translator::translate( const wchar_t *str,size_t sub )
{
if( sub == std::wstring::npos ) sub = wcslen( str );
buffer( sub + 1 );
m_buf[sub] = '\0';
return translate( str,sub,m_buf,sub );
}
};