Convert CString to string (VC6)
Asked Answered
H

2

3

I want to convert CString to string. (Yup. I know what am I doing. I know the returned string will be incorrect, if CString value range is outside ANSI, but That's Is OK!)

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 doesn't have CT2CA macro. How I can make the code to work as well in both VC6 and VC2008?

Haith answered 2/6, 2010 at 1:13 Comment(2)
Are you compiling Unicode? That is, does CString contain Unicode characters? Also, why oh why are you using VC6? It's twelve years old!!Verenaverene
We compile both in Unicode and Multi-byte. Hey! Ever heard about "Huge Legacy Code Base"?Haith
T
4

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

Thunderclap answered 2/6, 2010 at 1:21 Comment(1)
USES_CONVERSION; std::string str = T2CA((LPCTSTR)cString));Antoninus
P
2

Since you don't care about characters outside the ANSI range, brute force would 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;
}
Portal answered 2/6, 2010 at 2:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.