Leuel Asfaw
Leuel Asfaw

Reputation: 339

I am trying to create my own printf function, but I dont know how to include the format specifiers

I am trying to create my own printf function, here is my code:

#include <unistd.h>
#include <stdarg.h>

int write_char(char c);
int myPrintf(const char *format, ...);
int string_length(const char *string, int x);

int main(void)
{
    myPrintf("Let's try to printf a simple sentence.\n");
    myPrintf("Hello%d\n", 1);

    return (0);
}

int myPrintf(const char *format, ...)
{
    int i = 0, length = 0, j;

    length = string_length(format, j);

    va_list args;
    va_start(args, format);

    while (i < length)
    {
        if (format[i] != '%')
        {
           write_char(format[i]);
        } else
        {
            i++;
            switch(format[i])
            {
                case 'd':
                {
                    int x = va_arg(args, int);
                    write_char(x + '0');
                }
            }
        }
        i++;
    }
}

int string_length(const char *string, int x)
{
    if (*string != '\0')
    {
        return (string_length(string + 1, x + 1));
    }
        return (x); 
}

int write_char(char c)
{
    return(write(1, &c, 1));
}

But as I try to run my code, I get the following output:

Let's try to printf a simple sentence.
Hello
����|$����4����d���dM���������V�������4zRx
                                         ����&D$4`���@FJ
s                                                       �?:*3$"\x���tp���0�q���<E�C
������E�C
t:���=E�C
aW���*E�C
�@@
������o���
�
 �?Hx� ������ox���o���o`���o�=0@PLet's try to printf a simple sentence.
Hello
����|$����4����d���dM���������V�������4zRx
                                         ����&D$4`���@FJ
s                                                       �?:*3$"\x���tp���0�q���<E�C
������E�C
t:���=E�C
aW���*E�C
�A�7V@A�7V@
������o�3�7V�4�7V�3�7V
�
 QD���o�7VHx6�7V�5�7�  ������ox���o���o`5�7V���o�= 
.�� '0��p�"���]���!�p�7VSegmentation fault (core dumped)

It does print the string, but not when I include the format specifier to print integers:

myPrintf("Hello%d\n", 1);

Why is this happening?

Upvotes: 2

Views: 521

Answers (1)

Leuel Asfaw
Leuel Asfaw

Reputation: 339

I have solved the problem, here is the code:

int myPrintf(const char *format, ...)
{
    int i = 0, length = 0, j = 0;

    length = string_length(format, j);

    va_list args;
    va_start(args, format);

    while (i < length)
    {
        if (format[i] != '%')
        {
           write_char(format[i]);
        } else
        {
            i++;
            switch(format[i])
            {
                case 'd':
                {
                    int x = va_arg(args, int);
                    write_char(x + '0');
                }
            }
        }
        i++;
    }
    va_end(args);
    return (0);
}

Upvotes: 3

Related Questions