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;
};
inline wostream&
operator <<(wostream &os, const PrintF &pf){ os << pf.buf; return os; }