65.9K
CodeProject is changing. Read more.
Home

Replacing printf for use with MFC

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.53/5 (12 votes)

Nov 26, 2004

viewsIcon

34593

Replacing printf for use with MFC.

Introduction

This article explains a simple method to replace the printf function calls within an MFC application.

Background

Quite often we find very useful and well written code with lots of printf function calls. When we port this code into a MFC based GUI application we would certainly like the output of the printf to go into a listbox or a message box. Replacing a printf with a message box or list box display would take only a few lines of code. This is too hard especially if there are 100's of printfs all over.

Using the code

It would be very nice to replace all the printf calls with MFC_Printf in one shot just by pressing Ctrl+H shortcut, that is find and replace. Here is the construction of MFC_Printf(....):

class CMFCLog {
{
public:
  CMFCLog();
  {
  
  }
  ~CMFCLog();
  {

  }
  CListBox *m_pLB; // pointer to a CListBox

  void MFC_Printf(const char *formatstring,...)
  {
       CString    Str, s2;
    va_list    args;

    va_start(args, str);
              
    Str.FormatV(formatstring, args);

    Str.Replace('\n',' ');

    // Assuming that m_pLB is already initialized.
     m_pLB->AddString(Str);
     
    // We can even call a MessageBox here...
    
}
};
// This code is within the CPP file which contain lots of printf
static CMFCLog    Log;

....... Assign the m_pLB some where before calling MFC_Printf


// printf("\n\nThe Counter Values is: %d",i); is replaced with
Log.MFC_Printf("\n\nThe Counter Values is: %d", i);

Points of interest

We should always find simple solutions.