Write a customized printf function in C

S

sunfiresg

During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.



void printf (const char* format, ...);



The format can contain the following format specifiers:



format specifier := %[flags][width][.precision][modifier]type



where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }



The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.


Can any good C programmer give me a good answer? thanks!


richard
 
K

Karthik Kumar

sunfiresg said:
During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.



void printf (const char* format, ...);



The format can contain the following format specifiers:



format specifier := %[flags][width][.precision][modifier]type



where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }



The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.


Can any good C programmer give me a good answer? thanks!


richard

Use variable arguments facility to handle the args.
Rest should be fairly easy.
 
T

Trent Buck

Quoth sunfiresg on or about 2004-11-14:
Write a customized printf function in C

The GNU manpage for stdarg gives the following example:

The function foo takes a string of format characters and prints
out the argument associated with each format character based on the
type.

#include <stdio.h>
#include <stdarg.h>

void foo(char *fmt, ...) {
va_list ap;
int d;
char c, *p, *s;

va_start(ap, fmt);
while (*fmt)
switch(*fmt++) {
case 's': /* string */
s = va_arg(ap, char *);
printf("string %s\n", s);
break;
case 'd': /* int */
d = va_arg(ap, int);
printf("int %d\n", d);
break;
case 'c': /* char */
/* need a cast here since va_arg only
takes fully promoted types */
c = (char) va_arg(ap, int);
printf("char %c\n", c);
break;
}
va_end(ap);
}

-trent
 
J

J. J. Farrell

During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.



void printf (const char* format, ...);



The format can contain the following format specifiers:



format specifier := %[flags][width][.precision][modifier]type



where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }



The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.


Can any good C programmer give me a good answer? thanks!

Yes.
 
P

pete

sunfiresg said:
During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.



void printf (const char* format, ...);



The format can contain the following format specifiers:



format specifier := %[flags][width][.precision][modifier]type



where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }



The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.

Can any good C programmer give me a good answer? thanks!

I posted a min_printf here once or twice:
http://groups.google.com/[email protected]

It doesn't have support for any of
[flags][width][.precision][modifier]
 
S

sathya

sunfiresg said:
During an interview, I am asked to answer a question:

Printf is a major formatted output function provided by the standard C
library. Printf accepts a formatting string followed by a various
number of arguments to replace formatting specifiers in the formatting
string. You should implement the subset of the printf function
compliant to the following specification.



void printf (const char* format, ...);



The format can contain the following format specifiers:



format specifier := %[flags][width][.precision][modifier]type



where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }



The modifier h and l are applicable only to d and each of them is for
a short and a long integer respectively. The type c is to print a
character, d for an integer, and s for a character string. You should
use the sign when you print a number if the flag contains +. When - is
included in the flag, the output must be left aligned. If 0 is
included in the flag and the actual width of output is less than the
width specified in the format specifier, the output must be
zero-padded.

Can any good C programmer give me a good answer? thanks!

richard

I took this code from net long back. It does not carry the author name and
I did not test the code.
===============================untested code
starts==========================
/* printf.c */
extern putchar();

printf(fmt,firstparm)
char *fmt;
{
return uformat(putchar,fmt,&firstparm);
}

/* uformat - K&R C standard output formatting */

/************ Valid conversion specifications:

% {-} {nnn} {.} {mmm} {l} {d,o,x,u,c,s,e,f,g}

- = left-justify instead of right-justify
nnn = field width (0 start means pad with '0' instead of spaces)
mmm = precision (maximum # chars or # of digits to right of '.')
(default precision = 6)
l = long, not int.
d = decimal (int or long int)
o = unsigned octal (no leading zero)
x = unsigned hex (no leading 0x)
u = unsigned decimal (int or long int)
c = single character
s = string
e = [-]x.yyyyyyE[+/-]ee where precison = # y's
f = [-]xxx.yyyyyy where precision = # y's
(if precision==0, no decimal point is printed)
g = use %e or %f, whichever is shorter. (%f if equal)

*********************************************/
extern char *ultoa(),*ltoa(),*ecvt(),*fcvt();

int uformat( put, fmt, args )
/** Returns # of characters printed **/
int (*put)(), *args; char *fmt;
{
unsigned char c,left_justify,left_zpad,long_prefix,
conv[33],*p,*expp,expsign,*s;
double dblval; long int lival;
int dec,point,sign,pad1,pad2,pad3,pad4,cnt1,cnt2,explen,
retval,width,excess,pad,precision,exp,radix;

retval = 0;
while(c=*fmt++)
{
if(c!='%' || *fmt=='%')
{
if(c=='%') fmt++;
(*put)(c);
retval++;
}
else /* c==%, not %% */
{
pad1=pad2=pad3=pad4=sign=point=explen=cnt1=cnt2=0;
radix = 16; excess = 0; precision = -3;
if(left_justify = (*fmt=='-')) fmt++;
left_zpad = (*fmt=='0');
if((width = nextnum(&fmt)) < 0) width = 0;
if(*fmt == '.')
{fmt++; precision = nextnum(&fmt);}
if(long_prefix = (*fmt=='l')) fmt++;

switch(c=*fmt++)
{
case 'e': precision++;
case 'g':
case 'f':
dblval = *((double*)args)++;
if(precision<0) precision += 9; /* 6 or 7 */
if(c=='f')
p = fcvt(dblval, precision, &dec, &sign);
else
{
p = ecvt(dblval, precision, &dec, &sign);
exp = dec-1;
if(exp<0)
{exp = -exp; expsign = '-';}
else
expsign = '+';
conv[0] = '0';
ultoa( (long)exp, conv+1, 10);
expp = (conv[2]=='\0') ? conv : conv+1;
explen = strlen(expp)+2;
}
if(sign) sign = 1;
if(c=='g')
{
if(dec>=-3 && dec<=precision+5)
explen = 0;
s = p+strlen(p);
if(s!=p) while(--s!=p) if(*s=='0') *s='\0';
}
cnt1 = 1;
if(!explen)
{
if(dec<=0)
{
pad2 = 1;
pad3 = -dec;
}
cnt1 = (dec>0)? dec : 0;
}
cnt2 = strlen(p) - cnt1;
if(pad3+cnt2) point = 1;
pad = width - sign - pad2
- cnt1 - point - pad3
- cnt2 - explen;
if(pad<0)
{
pad = 0;
excess = -pad;
}
if(left_justify)
pad4 = pad;
else
pad1 = pad;
retval += width + excess;
break;

case 'd':
case 'o': radix -= 2; /* 8 */
case 'u': radix -= 6; /* 10 */
case 'x': /* 16 */

if(c=='d')
{
lival = long_prefix ? *((long*)args)++ : *args++;
p = ltoa( lival,conv,10 ); /* signed conversion */
}
else
{
lival = long_prefix ? *((unsigned long*)args)++ :
*((unsigned int*)args)++;
p = ultoa(lival,conv,radix); /* unsigned conversion */
}
if(precision <= 0) precision = 1;
cnt2 = strlen(p);
if(*p=='-')
{cnt2--; cnt1=1;}
if((pad3=precision-cnt1-cnt2) < 0) pad3 = 0;
if( (pad=width-cnt1-cnt2-pad3) < 0 )
{
excess = -pad;
pad = 0;
}
if(left_justify)
pad4 = pad;
else if(!left_zpad)
pad1 = pad;
else
pad3 += pad;
retval += width + excess;
break;

case 's': p = *((char**)args++);
case 'c': if(c=='c')
{
conv[1] = *args++;
conv[2] = '\0';
p = conv+1;
}
cnt1 = strlen(p);
if((precision>0)&&(precision<cnt1)) cnt1 = precision;
if( (pad=width-cnt1) < 0 )
{excess = -pad; pad = 0;}
if(left_justify)
pad4 = pad;
else
pad1 = pad;
retval += width + excess;
break;

default: (*put)(c); retval++; break;
}

while(pad1--) (*put)(' ');
if(sign) (*put)('-');
while(pad2--) (*put)('0');
while(cnt1--) (*put)(*p++);
if(point) (*put)('.');
while(pad3--) (*put)('0');
while(cnt2--) (*put)(*p++);
if(explen--)
{
(*put)('E');
(*put)(expsign);
while(--explen>=0) (*put)(*expp++);
}
while(pad4--) (*put)(' ');
}
}
return retval;
}

static int nextnum(f)
unsigned char **f;
{
register int r; char invalid,ch;
invalid = '\1';
for(r=0; (ch=**f, ch>='0' && ch<='9'); invalid = '\0')
{r = r*10 + (ch-'0'); (*f)++;}
return invalid ? -3 : r;
}

=============================untested code ends=======================




--
"Combination is the heart of chess"
A.Alekhine
Mail to:
sathyashrayan25 AT yahoo DOT com
(AT = @ and DOT = .)
 
M

Malcolm

sunfiresg said:
During an interview, I am asked to answer a question:

You should implement the subset of the printf function
compliant to the following specification.

void printf (const char* format, ...);

The format can contain the following format specifiers:

format specifier := %[flags][width][.precision][modifier]type

where flags := { + | - | 0 }

modifier := { h | l }

type := { c | d | s }


Can any good C programmer give me a good answer? thanks!
It's a nuisance of a job. In a real situation you would probably just call
vsprintf() to do your formatting, though I have found myself implementing
vsprintf()s in my time.

You scan the format string pushing out the input until you hit a %.
The format types don't have any aliases in the modifiers, so you can scan
the string to see what you are dealing with (you can get a brownie point by
asking what you are meant to do on bad input). Then you need to read the
fields.

If you are passed a %s your argument, via the the va_args family of
functions, is a char *, if a d it is an int, and if a c it is a char.
Strings and chars can basically be passed out. Integers have to be converted
to ascii, which you do by repeatedly taking mod 10 and dividing by ten, and
then reversing the result.

As a first pass, just ignore all the modifier fields and pass out the
straight results. This gives you 90% of the functionality.

Then you need to extend the program to take account of the various fields.
It is a lengthy job but not esepecially difficult.
 
L

Lawrence Kirby

On Mon, 15 Nov 2004 21:40:32 +0000, Malcolm wrote:

....
If you are passed a %s your argument, via the the va_args family of
functions, is a char *, if a d it is an int, and if a c it is a char.

But remember that in variable argument lists char arguments are promoted
to int, or in rare circumstances unsigned int.
Strings and chars can basically be passed out. Integers have to be
converted to ascii,

Converted to decimal textual form. There's no reason to assume ASCII.

which you do by repeatedly taking mod 10 and
dividing by ten, and then reversing the result.

Don't forget to add '0', which will produce a decimal digit in whatever
character set the implementation is using.

Lawrence
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top