Convert CString to String (VC6)

I want to convert a CString to a string. (I know what I'm doing. I know that the returned string will be incorrect if the range of CString values ​​is outside of ANSI, but that's fine!)

The following code will work under VC2008.

std::string Utils::CString2String(const CString& cString) 
{
    // Convert a TCHAR string to a LPCSTR
    CT2CA pszConvertedAnsiString (cString);

    // construct a std::string using the LPCSTR input
    std::string strStd (pszConvertedAnsiString);

    return strStd;
}

But VC6 does not have a CT2CA macro. How can I make the code work on both VC6 and VC2008?

+3
source share
2 answers

Microsoft claims that CT2CA replaces T2CA , so try the latter and see if it works.

+4
source

Since you don't care about characters outside the ANSI range, brute force will work.

std::string Utils::CString2String(const CString& cString) 
{
    std::string strStd;

    for (int i = 0;  i < cString.GetLength();  ++i)
    {
        if (cString[i] <= 0x7f)
            strStd.append(1, static_cast<char>(cString[i]));
        else
            strStd.append(1, '?');
    }

    return strStd;
}
+1
source

Source: https://habr.com/ru/post/1748077/


All Articles