CString Extensions for Resource Loading and String Formatting

The following classes were developed to simplify my life and clean up my code
and perhaps they can do the same for you. They are simple classes, but allow
an easy load of a string resource ( important for internationalization ) as
well as an easy way to format strings.

Class Definitions

// Load resource
class CResString : public CString
{
public:
 CResString(): CString() {};

 CResString(UINT nResID)
 {
  Init();
  VERIFY(LoadString(nResID) != 0);
  _ASSERTE( m_pchData );
 };

 void operator () (UINT nResID)
 {
  Init();
  VERIFY(LoadString(nResID) != 0);
  _ASSERTE( m_pchData );
 }
};

// Format 
class CFmtString : public CString
{
public:
 CFmtString(): CString() {};

 CFmtString( char *szFormat, ... )
 {
  Init();
  va_list argList;
  va_start( argList, szFormat );
  FormatV( szFormat, argList );
 };

 CFmtString( UINT uResID, ... )
 {
  Init();
  va_list argList;
  CResString sFormat( uResID );
  va_start( argList, sFormat );
  FormatV( sFormat, argList );
 };

 void operator () ( char *szFormat, ... )
 {
  Init();
  va_list argList;
  va_start( argList, szFormat );
  FormatV( szFormat, argList );
 }

 void operator () ( UINT uResID, ... )
 {
  Init();
  va_list argList;
  CResString sFormat( uResID );
  va_start( argList, sFormat );
  FormatV( sFormat, argList );
 }
};

Examples of Using the CResString Class

CResString sSection(IDS_DATAOBJECTSECTION);

// Use sSection

// ...

// Load another string

sSection(IDS_INVALIDOBJECT);

Example of Using the CFmtString Class

CFmtString sCommand(_T("SELECT %s FROM %s WHERE %s = %d"),
                    sColumn1, sTable, sColumn2, nID );

// Use sQuery

// ...

// Format another

sCommand(_T("UPDATE %s SET %s = %d WHERE %s = %d"),
         sTable, sColumn1, nValue, sColumn2, nID );

Downloads

Download source – 1 Kb

More by Author

Must Read