65.9K
CodeProject is changing. Read more.
Home

C++: Converting an MFC CString to a std::string

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.26/5 (21 votes)

Mar 30, 2011

CPOL
viewsIcon

70403

C++: Converting an MFC CString to a std::string

MFC includes its own string class, CString. I have sometimes found it useful to convert a CString to a standard C++ string (std::string). This is a function I wrote to do so:
std::string CStringToSTDStr(const CString& theCStr)
{
	// Convert the CString to a regular char array
	const int theCStrLen = theCStr.GetLength();
	char *buffer = (char*)malloc(sizeof(char)*(theCStrLen+1));
	memset((void*)buffer, 0, sizeof(buffer));
	WideCharToMultiByte(CP_UTF8, 0, static_cast(theCStr).GetBuffer(), theCStrLen, buffer, sizeof(char)*(theCStrLen+1), NULL, NULL);
	// Construct a std::string with the char array, free the memory used by the char array, and
	// return the std::string object.
	std::string STDStr(buffer);
	free((void*)buffer);
	return STDStr;
}