Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Simple manipulator for ostream for using printf style

0.00/5 (No votes)
1 Mar 2008CPOL 1  
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.

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

The Code

C++
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; }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)