473,387 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Write a customized printf function in C

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
Nov 14 '05 #1
7 2511
sunfiresg wrote:
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.
--
Karthik.
' Remove _nospamplz from my email to mail me. '
Nov 14 '05 #2
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
Nov 14 '05 #3
su*******@gmail.com (sunfiresg) wrote in message news:<62**************************@posting.google. com>...
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.
Nov 14 '05 #4
sunfiresg wrote:

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/groups?selm...mindspring.com

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

--
pete
Nov 14 '05 #5


sunfiresg wrote:
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,exple n,
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 = .)
Nov 14 '05 #6

"sunfiresg" <su*******@gmail.com> wrote
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.
Nov 14 '05 #7
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
Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Viviana Vc | last post by:
How can I programatically do the equivalent of the following: cacls "C:\Program Files\test" /T /G Everyone:f ? Thanks, Viv
7
by: Afifov | last post by:
Hello All, I have been working on some customized linux commands. I wrote the command mycpd dir1 dir2 that is supposed to copy a directory to another. I couldnt debug it in time. But here is wat it...
18
by: SSG | last post by:
How to write a object oriented program in c? give me one example....
4
by: childtobe | last post by:
I want to write the time to a file. (to implement this in an other piece of code that i've writen) For some reason he gives me a C2064 error when i try to put the time into a string. As you can...
6
by: ericunfuk | last post by:
printf("hello"); write(1,"hello",5); Are these two have the same effect?Only the 2nd one work for me sometimes?Are there situations that I can only use write() instead of printf()? Thanks
24
by: Bill | last post by:
Hello, I'm trying to output buffer content to a file. I either get an access violation error, or crazy looking output in the file depending on which method I use to write the file. Can anyone...
3
by: golden | last post by:
Hello, I am going to ask a question regarding write and lseek. I will provide code at the end of this, but first some background. I am trying to identify the cause of some latency in...
10
by: riva | last post by:
This is an interview question from: http://www.freshersworld.com/interview/technical_interview_C.htm Can You write a function similar to printf() ? I can only think using putchar() and casting...
1
by: xiao | last post by:
HI~ guys , I have a program here (Sorry it is very long about 240 lines.) It can read and write the header information successfully but it cannot write the array successfully. I guess there is...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.