This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Simple stream::form() replacement
- From: Dmitry Samersoff <dms at samersoff dot net>
- To: fnatter at gmx dot net, gcc at gcc dot gnu dot org
- Date: Sun, 05 May 2002 23:20:52 +0400
- Subject: Simple stream::form() replacement
Absence of stream::form and stream::vform functions in new libstdc++
really discurages me.
I have lots of code using it and migration from gcc 2.95 to 3.0.4
become a hard task.
Here is quick and simple replacement for it.
It missed some futures of real printf like floating point support, but
can handle the most necessary things:
%*d, %04ld, %20s
I'm going to include better version to next release of libdms (see
libdms.sourceforge.net) nearest future.
--
Dmitry Samersoff
dms@samersoff.net, http://devnull.wplus.net
ICQ: 3161705 irc://dalnet/samersoff
*There will come soft rains ...
/*
* $id$
*
*/
#include <stdarg.h>
using namespace std;
#include <iostream>
#include <iomanip>
ostream& sform(ostream& os, char *format, ... )
{
char* fptr = format;
va_list ap;
va_start(ap, format);
while(*fptr)
{
if (*fptr == '%')
{
++fptr;
/* init state */
int width = 0;
int modifier = 'i';
int fill = ' ';
os << nouppercase;
// set zerro fill if necessary
if (*fptr == '0')
{ fill = '0';
++fptr;
}
// extract width from varg or from fromat
if (*fptr == '*')
{
width = va_arg(ap, int);
++ fptr;
}
else
{
for(; (*fptr >= '0' && *fptr <= '9'); ++fptr)
{ width =width*10+(*fptr - '0');
}
}
if (*fptr == 'l') // handle %lX && %ld
{ modifier = 'l';
++fptr;
}
switch(*fptr)
{
case 'c':
{ int c = va_arg(ap, int);
os << (char) c;
}
break;
case 's':
{ char* s = va_arg(ap, char *);
if (width > 0) os << setw(width);
os << s;
}
break;
case 'd' :
{ if (width > 0) os << setw(width);
os << setfill( (char) fill);
os << dec;
if (modifier == 'l')
{
long ld = va_arg(ap, long);
os << ld;
}
else if (modifier == 'i')
{
int id = va_arg(ap, int);
os << id;
}
}
break;
case 'X' :
os << uppercase;
case 'x' :
{ if (width > 0) os << setw(width);
os << setfill( (char) fill);
os << hex;
if (modifier == 'l')
{
long ld = va_arg(ap, long);
os << ld;
}
else if (modifier == 'i')
{
int id = va_arg(ap, int);
os << id;
}
}
break;
}
++fptr; // don't copy format characters
} // if %
os << (char) *fptr;
++fptr;
} // while
return os;
}
int main(void)
{
sform(cerr, "%s: %04lX %s\n", "NUMBER", 12, "ok" );
}