我想编写printf函数。问题是我的代码变得非常混乱,我需要一些帮助来尝试使其组织起来(希望)。我被告知应该使用“数组函数指针”,所以我在下面尝试(ft_print_it),正如你所看到的,但我不知道如何构造我的代码,以便我可以使用大量的函数指针来放置每个函数都像int_decimal_octal和朋友。你能帮助我吗?我可以从哪里打电话给他们?使用函数指针数组编码printf
另外,我意识到下面的小函数(cast_in_short)给了我和printf相同的结果,如果我用我的ft_putnbr写出输出的话。我的第二个问题是:我可以让我的printf使用这样的小功能吗?非常感谢。
int cast_in_short(int truc)
{
truc = (short)truc;
return (truc);
}
/*
here in the main I noticed that I get the same behaviour
between my putnbr and printf thanks to my little function
cast_in_short. This is the kind of function I want to use
and put into an array of pointer of functions in order
to make my printf work
*/
int main()
{
int n = 32769;
n = cast_in_short(n);
ft_putnbr(n);
printf("\n");
return (0);
}
/* function to launch ft_print_it */
int ft_print_str_spec(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putstr(va_arg(ap, char *));
else
{
ft_nbzero(ap, flag, 0);
ft_putstr(va_arg(ap, char *));
}
return (1);
}
int ft_print_oct(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putnbr(decimal_octal((va_arg(ap, int))));
else
{
ft_nbzero(ap, flag, 1);
ft_putnbr(decimal_octal((va_arg(ap, int))));
}
return (1);
}
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
char *ft_strjoin2(char const *s1, char const c);
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
int decimal_octal(int n) /* Function to convert decimal to octal */
{
int rem;
int i;
int octal;
i = 1;
octal = 0;
while (n != 0)
{
rem = n % 8;
n /= 8;
octal += rem * i;
i *= 10;
}
return (octal);
}
您是否在某些免费软件C标准库中研究了'printf'的源代码? –
是的,我尝试过,但他们不使用函数指针数组... – zakk8889
你似乎对C相当陌生,你为什么要实现像printf这样的复杂函数? – Stuart