| Write your own printf() functi... | |||||||
|
30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied. Book (308 Pages):
![]() Video (One Hour):
![]() Resume Review (24 - 48hr)
All Products / Services
|
|||||||
Agree - not acceptable. Whoever asked you is a duh!
May be he wanted to hear about varargs - and how you efficiently code integers into strings...but that is it. Nothing more.
i agree.....its not possible to code the whole function during an interview, the interviewer might have been interested in knowing about stdarg.h etc...
a lame attempt using stdarg
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include<string.h>#define STDOUT 1
#define MAX_INT_LEN 10
//function foo taken from manpages of stdarg
void Printf(char *fmt, ...)
{
va_list ap;
int d;
char c, *s;
va_start(ap, fmt);
while (*fmt)
switch (*fmt++) {
case 's': /* string */
s = va_arg(ap, char *);
write(STDOUT, s, strlen(s));
break;
case 'd': /* int */
d = va_arg(ap, int);
s = malloc(MAX_INT_LEN);
sprintf(s, "%d", d); // lame attempt to convert int to string, no itoa() in linux :(
write(STDOUT, s, strlen(s));
free(s);
break;
case 'c': /* char */
/* need a cast here since va_arg only
takes fully promoted types */
c = (char) va_arg(ap, int);
write(STDOUT, &c, 1);
break;}
va_end(ap);
}int main() {
Printf("%s %d %c", "hello world", 123456 , 's');
}
To convert an int to string:
char* convert(int x) {
int t = x;
int i = 2;
while (t = t / 10) ++i;
char* s = new char[i];
s[--i] = '\0';
while (i) s[--i] = 48 /* int('0') */ + (x % 10), x = x / 10;
return s;
}
Dump question! Did the interviewer ask you to write DOS on 8 bit processor?
How many formats do you have to deal with in printf()?