Thursday, February 18, 2010

MyPrint Challenge

Here is my code for the MyPrint challange that was assigned today in class.

The code is as follows:

void main ()
{
MyPrint("int %d, char %c, string %s, hex %x, float %f", 2, 'A', "hello", 16, 12.34567);

}

int MyPrint(char* str, int a, char b, const char c[], int d, float f)
{
int i = 0;

while (str[i] != '\0')
{
if (str[i] == '%' && str[i+1] == 'd')
{
i++;
i++;
putint (a);
}
if (str[i] == '%' && str[i+1] == 'c')
{
i++;
i++;
_putch (b);
}
if (str[i] == '%' && str[i+1] == 's')
{
i++;
i++;
_cputs (c);
}
if (str[i] == '%' && str[i+1] == 'x')
{
i++;
i++;
puthex (d);
}
if (str[i] == '%' && str[i+1] == 'f')
{
i++;
i++;
putdub (f);
}
_putch(str[i]);
i++;
}

_getch();

return 0;
}

void puthex(int val)
{
char str[20] = "";
int i = 0, num;
while(val != 0)
{
str[i] = (val % 16) + 48;
val = val/16;
i++;
}

for (i = 0;i <= 19;i++)
{
if (str[i] != '\0')
{
num = str[i] - 48;
if (num > 9)
str[i] += 7;
}
}

for (i = 19; i >= 0;i--)
{
if (str[i] != '\0')
_putch(str[i]);
}
}
void putdub (double val)
{
char buff [20] = "";
int asdf = val;
val = val - asdf;
int i, j, start;
j = 0;

for (i = 10000; i >= 1;i = i/10)
{
if (asdf >= i)
{
start = asdf/i;
asdf = asdf % i;
buff [j] = start + 48;
j++;
}
}
buff [j] = '.';
j++;

asdf = val/0.01;
buff [j] = (asdf/10) + 48;
j++;
buff[j] = (asdf%10) + 48;

_cputs (buff);
}

void putint(int val){
char temp[20] = "";
int i = 0;
int j = 0;
int length = 0;
int scale = 1;
if (val == 0)
_putch('0');
else{
for (i = 1, length = 0; val / i != 0 ; i *= 10, length++);
if (val > 0) {
for (i = 0; i < length; i++){
scale = 1;
for (j = 0; length - j > i + 1; j++)
scale *= 10;
temp[i] = (val / scale) % 10 + 48;
}
temp[i] = '\0';
}
else {
val *= -1;
temp[0] = '-';
for (i = 0; i < length; i++){
scale = 1;
for (j = 0; length - j > i + 1; j++)
scale *= 10;
temp[i+1] = (val / scale) % 10 + 48;
}
temp[i+1] = '\0';
}
}
_cputs (temp);
}

Since I never did the previous challenge, I was looking through the CDOT planet feed for someone who did the first one, and luckily I found one. I used Shengwei's solution. I hope this is acceptable considering it is an open source subject. Anyways thanks for posting your code shengwei, made my life a little easier!

As far as the code that I wrote goes, it was pretty straight forward. I decided the easiest way to go about it was to use _putch and _cputs for displaying single characters and strings. The hex function was pretty simple as far as coding goes, although it took me a while to remember how to convert from decimal to hex, its been a while ahah. The decimal function was the trickiest for me for some reason. I kept thinking of other ways to do mid way through writing the code for the function, causing me to stop and rethink my approach many times.

Any ways hope this is what your looking for Fardad. I look forward to 10% on the test :D

No comments:

Post a Comment