wstring to string and vice versa

昨天遇到了wstring to string的问题,上网搜索了一下,现在倒是解决了,就是还想知道还有哪些解决方案。希望有知道的,我这里没有的回复一下,谢谢了。

1. 使用window 提供的WideCharToMultiByte和MultiByteToWideChar,就是用来转换的很好用

2.使用runtime提供的_wcstombs_s_l和_mbstowcs_s_l,就是用来转换的很好用,据说可移植,我现在懂得不多不敢乱说。
我使用的是runtime提供的函数,在下面会提供整个cpp文件,包括简单的测试。

还有一些方法,我使用之后发现对中文不好用出来的是0xffff。
使用widen() or narrow(),std::codecvt class,这些都没细看,反正现在好用了,等有时间在研究吧。
网上还有一个CStdString类,但是对中文无法使用转换之后就不对了。

boost的lexical_cast也无法转换,没有具体细看。有人写了个lexical_cast的实现使用
for(unsigned int i= 0; i < arg.size(); ++i)
  {
   result += std::use_facet<std::ctype<wchar_t> >(loc).widen(arg[i]);
  }
来转换,对中文也不好用。有时间在研究吧。
奇怪了插入代码里面有java,C#,怎么就没有C/C++呢。

#include 
  
  
#include 
  
  
#include 
  
  
#include 
  
  
#include 
  
  
// compile with: /EHsc
#define _INTL
#include 
  
  

#include 
  
  
using namespace std;

//runtime routine
wstring s2w(const string& wstr);
string w2s(const wstring& wstr);

//cpp routine
wstring narrow2widen(const string& str);
string widen2narrow(const wstring& wstr);

/*
	demonstrate how to convert wstring to string 
	and vice versa
*/
int main()
{
	wstring wstr1 = _T("中文 english ");
	string str1 = "中文 english";

	//string str = boost::lexical_cast
  
  ( wstr1.c_str() );
	//wstring wstr = boost::lexical_cast
  
  ( str1.c_str() );//msvcp90d.dll not found error
	
	wstring wstr2 = s2w(str1);
	string str2 = w2s(wstr2);
	wcout.imbue(locale("chs"));
	wcout<buf( wstr.size()*2 + 1 );
	_locale_t local = _create_locale(LC_ALL,"chs");
	//if failed set buf empty string and num = 0
	_wcstombs_s_l(&num, &buf[0], buf.size(),wstr.c_str(),_TRUNCATE,local);
	_free_locale(local);
	return &buf[0];
}

wstring s2w(const string& str)
{
	size_t num = 0;
	vector
  
  buf( str.size()*2 + 2 );
	_locale_t local = _create_locale(LC_ALL,"chs");
	//if failed set buf empty string and num = 0
	_mbstowcs_s_l(&num, &buf[0], buf.size(),str.c_str(),_TRUNCATE,local);
	_free_locale(local);
	return &buf[0];
}


/**
use c++ class do it
*/
string widen2narrow(const wstring& wstr)
{
	char* pszNext = NULL;
	const wchar_t* pwszNext = NULL;
	mbstate_t state = {0};
	vector
  
  vBuf( wstr.size() * 2 + 1 );
	locale loc("CHS");
	if ( codecvt_base::ok != use_facet >
		( loc ).out( state,wstr.c_str(),wstr.c_str() + wstr.size(), pwszNext,
		&vBuf[0], &vBuf.back(), pszNext ) )
	{
		return "";
	}else
		return &vBuf[0];

}

/**
use c++ class do it
*/
wstring narrow2widen(const string& str)
{
	wchar_t* pwszNext = NULL;
	const char* pszNext = NULL;
	mbstate_t state = {0};
	vector
  
  vBuf( str.size() * 2 + 2 );
	locale loc("CHS");
	if ( codecvt_base::ok != use_facet >
		( loc ).in( state,str.c_str(),str.c_str() + str.size(), pszNext,
		&vBuf[0], &vBuf.back(), pwszNext ) )
	{
		return L"";
	}else
		return &vBuf[0];

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值