Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
29 Mar 2011 1  
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<cstring>(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;
}</cstring>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here