65.9K
CodeProject is changing. Read more.
Home

Simple manipulator for ostream for using printf style

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Mar 1, 2008

CPOL
viewsIcon

18730

A simple manipulator class for using printf style in ostream

Introduction

Some people often wishes a "printf" style for using with the IO-Streams like the (w)stringstream class.

With some lines of code and the knowledge of manipulators, this is not a big deal. In this example I use the Unicode variant of the stringstream class. But with some changes it works also with the multibyte variants.

Using the code

Put the manipulator in your stream ;) Here I use the Unicode variant of the stringstream class.

            wstringstream stream;
            stream << L"All about this " << PrintF(L"%d", 20) << endl;           
          

The Code

class PrintF
{
public:
 ~PrintF(){ delete[] buf;}
    explicit PrintF(const WCHAR* fmt,...){
        va_list args;
        va_start(args, fmt);
        size_t len = _vscwprintf(fmt, args ) + 1;
        buf = new WCHAR[len+1];
        vswprintf_s( buf, len, fmt, args); 
    }
    friend wostream&  operator <<(wostream &os, const PrintF &pf);
private:
    WCHAR* buf;
};

//manipulator
inline wostream& 
operator <<(wostream &os, const PrintF &pf){ os << pf.buf; return os; }