wstring转string和string转wstring

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/kezunhai/article/details/48369897
//=================================================================================
//	Narrow2Wide()
//=================================================================================
wstring Narrow2Wide(const std::string& narrowString)
{
	int m_codepage = _getmbcp();

	int numChars =
	::MultiByteToWideChar( m_codepage, 
						   MB_PRECOMPOSED, 
						   narrowString.c_str(), 
						   -1, 
						   0, 
						   0
						  );
	_ASSERT(numChars);
//	TRACE("Number of characters in the string is %d", numChars);

	wchar_t* test = new wchar_t[numChars+1];
	numChars =
	::MultiByteToWideChar( m_codepage, 
						   MB_PRECOMPOSED, 
						   narrowString.c_str(), 
						   -1, 
						   test, 
						   numChars
						  );

	std::wstring temp(test);
	delete []test;

	return temp;
}


//=================================================================================
//	Wide2Narrow()
//=================================================================================
string Wide2Narrow(const wstring& wideString)
{
	int m_codepage = ::_getmbcp();

	int result = ::WideCharToMultiByte( 
							m_codepage,  // Code page
							0,		// Default
							wideString.c_str(), // WCS buffer
							-1,		// Assume null terminated str, calclate length auto
							0,      // Buffer to receive MBCS string
							0,		// Length of MB buffer ( 0 -> return length required )
							0,		// lpdefaultChar
							0		// lpUsedDefaultChar
						 );
	_ASSERT(result);
	char *test = new char[result+1]; 
	result = ::WideCharToMultiByte( 
							m_codepage,  // Code page
							0,		// Default
							wideString.c_str(), // WCS buffer
							-1,		// Assume null terminated str, calclate length auto
							test,   // Buffer to receive MBCS string
							result,	// Length of MB buffer ( 0 -> return length required )
							0,		// lpdefaultChar
							0		// lpUsedDefaultChar
						 );

	std::string temp(test);
	delete []test;

	return temp;
}

猜你喜欢

转载自blog.csdn.net/kezunhai/article/details/48369897
今日推荐