gpt4 book ai didi

C : Create a function to diplay number just with "write" function

转载 作者:行者123 更新时间:2023-11-30 20:14:39 25 4
gpt4 key购买 nike

如何编写一个基本函数,仅使用 #include<unistd.h> 中包含的“write”函数来显示数字?

示例:

ft_putnbr.c

int ft_putnbr(int nbr)
{
write(1, &nbr, sizeof(int));
return (0);
}

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

main.c

int     ft_putnbr(int nbr);
int ft_putchar(char c);

int main(void)
{
ft_putnbr(6);
ft_putchar('\n');
ft_putchar('a');
return (0);
}

ft_putchar 工作正常,但我想用我的“ft_putnbr”函数对数字做同样的事情。

编译或执行软件时没有错误,但显示的是空白而不是我的号码。

最佳答案

您必须将 int 转换为 char* 表示形式(ASCII 翻译)。例如:

int nbr = 1234;
char str[16]; /* max size expected: 15 digits + 1 null character */
sprintf(str, "%d", nbr);

然后:

write(1, str, strlen(str));

您需要包括这些:

#include <stdio.h>
#include <string.h>

关于C : Create a function to diplay number just with "write" function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com