Learning Hub Search Ctrl K

MFC › 2. Application Architecture

CString and Collection Classes

CString, CArray, CList, CMap and conversion pitfalls.

beginner #mfc#cstring#carray#clist#cmap#cstringarray#collections#conversions

Explanation

CString is MFC’s reference-counted string. It’s an alias of CStringT<TCHAR, ...> and shared with ATL, so it works in any Windows C++ project. With Unicode builds a CString holds UTF-16 wchar_t.

Frequent members: GetLength, IsEmpty, Left/Right/Mid(n), Find, Replace, Remove, Trim/TrimLeft/TrimRight, MakeUpper/MakeLower, Format, Compare/CompareNoCase, GetBuffer/ReleaseBuffer, operator[], +, +=, and implicit conversion to LPCTSTR.

Conversions: use the ATL conversion macros: CT2A(s) (to char*), CA2T(a), CT2W, CW2T. Conversion from numbers: s.Format(_T("%d"), n), _ttoi, _tstof.

Template collections (header <afxtempl.h>, included by afxwin.h in recent versions):

Class Like Key operations
CArray<T, ARG_T> std::vector Add, GetAt, SetAt, InsertAt, RemoveAt, GetSize, SetSize, []
CList<T, ARG_T> std::list AddTail, AddHead, GetHeadPosition, GetNext(pos), RemoveAt(pos)
CMap<K, ARG_K, V, ARG_V> std::unordered_map SetAt, Lookup(key, val), RemoveKey, GetStartPosition, GetNextAssoc
CStringArray, CStringList, CMapStringToString, CPtrArray typed/legacy variants

ARG_T is how the element is passed to functions (use const T& for classes).

Example

#include <afxwin.h>
#include <afxtempl.h>
#include <iostream>

int _tmain() {
    if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;

    // --- CString
    CString s = _T("  Hello, MFC World  ");
    s.Trim();
    std::wcout << (LPCTSTR)s << L"|" << s.GetLength() << L"\n";                  // Hello, MFC World|16
    s.Replace(_T("MFC"), _T("C++"));
    std::wcout << (LPCTSTR)s.Left(5) << L" " << s.Find(_T("World")) << L"\n";    // Hello 11

    CString msg;
    msg.Format(_T("%s has %d chars (%.1f%%)"), (LPCTSTR)s, s.GetLength(), 12.5);
    std::wcout << (LPCTSTR)msg << L"\n";

    CT2A ansi(s);                                   // UTF-16 -> ANSI (code page); freed with 'ansi'
    std::cout << strlen(ansi) << "\n";              // 16

    CString u = _T("abc");
    u.MakeUpper();
    std::wcout << (u == _T("ABC")) << (u.CompareNoCase(_T("abc")) == 0) << L"\n";   // 11

    // --- CArray
    CArray<int, int> nums;
    for (int i = 1; i <= 5; ++i) nums.Add(i * i);
    nums.InsertAt(0, 100);
    nums.RemoveAt(1);
    int sum = 0;
    for (INT_PTR i = 0; i < nums.GetSize(); ++i) sum += nums[i];
    std::wcout << nums.GetSize() << L" items, sum " << sum << L"\n";            // 5 items, sum 154

    // --- CList: iterate with POSITION
    CList<CString, const CString&> names;
    names.AddTail(_T("Ann"));
    names.AddTail(_T("Bob"));
    names.AddHead(_T("Zed"));
    for (POSITION pos = names.GetHeadPosition(); pos != nullptr; )
        std::wcout << (LPCTSTR)names.GetNext(pos) << L" ";                      // Zed Ann Bob
    std::wcout << L"\n";

    // --- CMap
    CMap<CString, LPCTSTR, int, int> ages;
    ages[_T("Ann")] = 30;
    ages.SetAt(_T("Bob"), 25);
    int age = 0;
    if (ages.Lookup(_T("Ann"), age)) std::wcout << L"Ann is " << age << L"\n";   // Ann is 30
    std::wcout << ages.GetCount() << (ages.Lookup(_T("Zed"), age) ? L" found" : L" no Zed") << L"\n";

    CStringArray words;
    words.Add(_T("pear")); words.Add(_T("fig"));
    std::wcout << (LPCTSTR)words[1] << L" " << words.GetSize() << L"\n";        // fig 2
    return 0;
}

Common pitfalls

  • GetBuffer() returns a writable pointer: you must call ReleaseBuffer() afterwards, otherwise the length is wrong.
  • CString::Format with a wrong specifier (%d for a string) crashes just like printf. Cast CString arguments with (LPCTSTR).
  • A CString converts implicitly to LPCTSTR, but not to std::string/std::wstring: build with std::wstring(s.GetString()).
  • CArray::operator[] asserts in debug and is undefined in release when out of range; SetAtGrow extends the array.
  • Index and size types are INT_PTR, not size_t: comparing with unsigned types gives sign warnings.
  • Removing elements in a CList while iterating needs the position saved before GetNext.
  • CMap with a custom key type needs a HashKey specialization.

Legacy vs modern

CArray, CList and CMap predate the STL and aren’t iterator-based; you cannot use them with <algorithm> directly. In new code prefer std::vector<T>, std::list<T> and std::unordered_map<K,V>; convert at the MFC API boundary. Compare with std::string.

Exercises

1. What does CString s; s.Format(_T("%03d"), 7); produce?

007: the usual printf rules apply.