Thursday, February 18, 2010

Challenges solution : MyPrint()

Here is my solution for MyPrint().

#include <stdio.h>
#include <conio.h>
#include <stdarg.h>
void print_int_hex(int val,int alg)
{
int i;
if (val==0)
{
_putch('0');
}
else
{
if (val/alg)
{
i = val % alg;
print_int_hex(val/alg,alg);
}
else
i = val % alg;
if (i>9)
{
i=i-10+'a';
_putch(i);
}
else
_putch(i?i+48:48);
}
}

void print_float(double val)
{
int temp = val *100;

if (val==0)
{
_putch('0');
}
else
{
print_int_hex(temp/100,10);
_putch('.');
print_int_hex(temp%100,10);
}
}

void MyPrint(char* pString,...)
{
int i=0;
int ch;
const char* str;
double f;

va_list args;
va_start(args, pString);
while (pString[i])
{
if (pString[i]=='%')
{
i++;
switch(pString[i])
{
case 'c':
ch = va_arg(args, int);
_putch(ch);
break;
case 's':
str = va_arg(args, const char*);
_cputs(str);
break;
case 'd':
ch = va_arg(args,int);
if (ch<0)
{
_putch('-');
ch=ch*(-1);
}
print_int_hex(ch,10);
break;
case 'x':
case 'X':
ch = va_arg(args, int);
print_int_hex(ch,16);
break;
case 'f':
f = va_arg(args, double);
print_float(f);
break;
}
i++;
}
_putch(pString[i]);
i++;
}
va_end(args);
}

int main()
{
MyPrint("int %d, char %c, string %s, hex %x, float %f", -102, 'A', "hello", 31, 12.34567);
return 0;
}

Result as:
int -102, char A, string hello, hex 1f, float 12.34
For float, I thought might be have better solution.

1 comment:

  1. Review my code, I found a bug here. In case of asking to print character "%" itself. I need to add one more case in switch statement in function MyPrint(), as:

    default:
    _putch('%');
    break;

    ReplyDelete