Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Replacing printf for use with MFC

0.00/5 (No votes)
26 Nov 2004 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here