CString Formatting and Message-Box Display

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at CString Formatting and Message-Box Display.

A number of functions are provided to format and parse CString objects. You can use these functions whenever you have to manipulate CString objects, but they are particularly useful for formatting strings that will appear in message-box text.

This group of functions also includes a global routine for displaying a message box.

CString Functions

AfxExtractSubString Extracts substrings separated by a single character from a given source string.
AfxFormatString1 Substitutes a given string for the format characters "%1" in a string contained in the string table.
AfxFormatString2 Substitutes two strings for the format characters "%1" and "%2" in a string contained in the string table.
AfxMessageBox Displays a message box.

AfxExtractSubString

This global function can be used to extract a substring from a given source string.

BOOL AFXAPI AfxExtractSubString (
    CString& rString,  
    LPCTSTR lpszFullString,  
    int iSubString,  
    TCHAR chSep  = '\n'); 

Parameters

rString

  • Reference to a CString object that will receive an individual substring.

lpszFullString

  • String containing the full text of the string to extract from.

iSubString

  • Zero-based index of the substring to extract from lpszFullString.

chSep

  • Separator character used to delimit substrings.

Return Value

TRUE if the function successfully extracted the substring at the provided index; otherwise, FALSE.

Remarks

This function is useful for extracting multiple substrings from a source string when a known single character separates each substring. This function searches from the beginning of the lpszFullString parameter each time it is called.

This function will return FALSE if either lpszFullString is set to NULL or the function reaches the end of lpszFullString without finding iSubString+1 occurrences of the specified separator character. The rString parameter will not be modified from its original value if lpszFullString was set to NULL; otherwise, the rString parameter is set to the empty string if the substring could not be extracted for the specified index.

Example

      // The following example extracts a series of name, value pairs from a
      // given source string:
       
      // Input string consisting of a number of name, value pairs
      LPCTSTR lpszSource = _T("\"Name\"=\"John Smith\"\n")
         _T("\"Company\"=\"Contoso, Ltd\"\n\"Salary\"=\"25,000\"");

      CString strNameValue; // an individual name, value pair

      int i = 0; // substring index to extract
      while (AfxExtractSubString(strNameValue, lpszSource, i))
      {
         // Prepare to move to the next substring
         i++;

         CString strName, strValue; // individual name and value elements

         // Attempt to extract the name element from the pair
         if (!AfxExtractSubString(strName, strNameValue, 0, _T('=')))
         {
            // Pass an error message to the debugger for display
            OutputDebugString(_T("Error extracting name\r\n"));
            continue;
         }

         // Attempt to extract the value element from the pair
         if (!AfxExtractSubString(strValue, strNameValue, 1, _T('=')))
         {
            // Pass an error message to the debugger for display
            OutputDebugString(_T("Error extracting value element\r\n"));
            continue;
         }

         // Pass the name, value pair to the debugger for display
         CString strOutput = strName + _T(" equals ") + strValue + _T("\r\n");
         OutputDebugString(strOutput);
      }

AfxFormatString1

Substitutes the string pointed to by lpsz1 for any instances of the characters "%1" in the template string resource identified by nIDS.

void  AfxFormatString1(
    CString& rString,  
    UINT nIDS,  
    LPCTSTR lpsz1); 

Parameters

rString
A reference to a CString object that will contain the resultant string after the substitution is performed.

nIDS
The resource ID of the template string on which the substitution will be performed.

lpsz1
A string that will replace the format characters "%1" in the template string.

Remarks

The newly formed string is stored in rString. For example, if the string in the string table is "File %1 not found", and lpsz1 is equal to "C:\MYFILE.TXT", then rString will contain the string "File C:\MYFILE.TXT not found". This function is useful for formatting strings sent to message boxes and other windows.

If the format characters "%1" appear in the string more than once, multiple substitutions will be made.

Example

void DisplayFileNotFoundMessage(LPCTSTR pszFileName)
{
   CString strMessage;

   // The IDS_FILENOTFOUND string resource contains "Error: File %1 not found"
   AfxFormatString1(strMessage, IDS_FILENOTFOUND, pszFileName);
   // In the previous call, substitute the actual file name for the
   // %1 placeholder
   AfxMessageBox(strMessage);  // Display the error message
}

AfxFormatString2

Substitutes the string pointed to by lpsz1 for any instances of the characters "%1", and the string pointed to by lpsz2 for any instances of the characters "%2", in the template string resource identified by nIDS.

void AfxFormatString2(
    CString& rString,  
    UINT nIDS,  
    LPCTSTR lpsz1,  
    LPCTSTR lpsz2); 

Parameters

rString
A reference to the CString that will contain the resultant string after the substitution is performed.

nIDS
The string table ID of the template string on which the substitution will be performed.

lpsz1
A string that will replace the format characters "%1" in the template string.

lpsz2
A string that will replace the format characters "%2" in the template string.

Remarks

The newly formed string is stored in rString. For example, if the string in the string table is "File %1 not found in directory %2", lpsz1 points to "MYFILE.TXT", and lpsz2 points to "C:\MYDIR", then rString will contain the string "File MYFILE.TXT not found in directory C:\MYDIR"

If the format characters "%1" or "%2" appear in the string more than once, multiple substitutions will be made. They do not have to be in numerical order.

Example

void DisplayFileNotFoundMessage(LPCTSTR pszFileName, LPCTSTR pszDirectory)
{
   CString strMessage;

   // The IDS_FILENOTFOUND string resource contains "Error: File %1 not 
   // found in directory %2"
   AfxFormatString2(strMessage, IDS_FILENOTFOUND2, pszFileName, pszDirectory);
   // In the previous call, substitute the actual file and directory 
   // names into the message string
   AfxMessageBox(strMessage);  // Display the error message
}

AfxMessageBox

Displays a message box on the screen.

int AfxMessageBox(
    LPCTSTR lpszText,  
    UINT nType = MB_OK,  
    UINT nIDHelp = 0);

int AFXAPI AfxMessageBox(
    UINT nIDPrompt,  
    UINT nType = MB_OK,  
    UINT nIDHelp = (UINT) -1); 

Parameters

lpszText
Points to a CString object or null-terminated string containing the message to be displayed in the message box.

nType
The style of the message box. Apply any of the message-box styles to the box.

nIDHelp
The Help context ID for the message; 0 indicates the application's default Help context will be used.

nIDPrompt
A unique ID used to reference a string in the string table.

Return Value

Zero if there is not enough memory to display the message box; otherwise, one of the following values is returned:

  • IDABORT The Abort button was selected.

  • IDCANCEL The Cancel button was selected.

  • IDIGNORE The Ignore button was selected.

  • IDNO The No button was selected.

  • IDOK The OK button was selected.

  • IDRETRY The Retry button was selected.

  • IDYES The Yes button was selected.

If a message box has a Cancel button, the IDCANCEL value will be returned if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing the ESC key has no effect.

The functions AfxFormatString1 and AfxFormatString2 can be useful in formatting text that appears in a message box.

Remarks

The first form of this overloaded function displays a text string pointed to by lpszText in the message box and uses nIDHelp to describe a Help context. The Help context is used to jump to an associated Help topic when the user presses the Help key (typically F1).

The second form of the function uses the string resource with the ID nIDPrompt to display a message in the message box. The associated Help page is found through the value of nIDHelp. If the default value of nIDHelp is used (– 1), the string resource ID, nIDPrompt, is used for the Help context. For more information about defining Help contexts, see Technical Note 28.

Example

   // A simple message box, with only the OK button.
   AfxMessageBox(_T("Simple message box."));

   // A message box that uses a string from a string table
   // with yes and no buttons and the stop icon.
   // NOTE: nStringID is an integer that contains a valid id of
   // a string in the current resource.
   AfxMessageBox(nStringID, MB_YESNO|MB_ICONSTOP);

See Also

Macros and Globals
CStringT Class