为什么我的代码输出的是”2467135″而不是”1234567″?

huangapple go评论79阅读模式
英文:

Why does the my code output "2467135" instead of "1234567"?

问题

我对以下代码有一个问题。为什么代码的输出变成了2467135?它首先给出了我的自定义函数的输出,然后是write函数的输出,最后是printf函数的输出。这种行为的原因是什么?

int ft_printf(const char *s, ...)
{
    va_list ap;
    int i;
    int len;

    len = 0;
    i = 0;
    va_start(ap, s);
    while (s[i])
    {
        if (s[i] == '%')
        {
            len += ft_formats(s, ap, ++i);
        }
        else
            len += ft_putchar(s[i]);
        i++;
    }
    va_end(ap);
    return (len);
}

#include <stdio.h>

int main()
{
    printf("1");
    ft_printf("2");
    printf("3");
    ft_printf("4");
    printf("5");
    ft_printf("6");
    write(1,"7",1);
}

我期望的输出是1234567,但实际输出却是2467135

英文:

I have a question about the following code. Why is the output of the code becoming 2467135? It first gives the output of my own function, then of the write function, and finally of the printf function. What is the reason for this behavior.

int	ft_printf(const char *s, ...)
{
	va_list	ap;
	int		i;
	int		len;

	len = 0;
	i = 0;
	va_start(ap, s);
	while (s[i])
	{
		if (s[i] == &#39;%&#39;) 
		{
			len += ft_formats(s, ap, ++i);
		}
		else
			len += ft_putchar(s[i]);
		i++;
	}
	va_end(ap);
	return (len);
}

#include &lt;stdio.h&gt;

int main()
{
	printf(&quot;1&quot;);
	ft_printf(&quot;2&quot;);
	printf(&quot;3&quot;);
	ft_printf(&quot;4&quot;);
	printf(&quot;5&quot;);
	ft_printf(&quot;6&quot;);
	write(1,&quot;7&quot;,1);
}

I was expecting 1234567 but the output came out as 2467135

答案1

得分: 2

ft_printfprintfwrite的输出不会按照源代码的顺序显示,这是因为缓冲机制的存在:默认情况下,stdout对终端是行缓冲的,这意味着数字135会被存储在输出流缓冲区中,直到输出换行符或者调用fflush(stdout)。在程序退出时,所有的流都会被刷新和关闭,因此135会出现在输出的最后。

如果在向stdout写入任何内容之前,使用setvbuf(stdout, NULL, _IONBF, 0)stdout配置为无缓冲,就可以获得123456的输出结果。

英文:

The output of ft_printf, printf and write does not appear in the source order because of bufferisation: stdout is line buffered to a terminal by default, which means the individual digits 1, 3 and 5 are stored in the output stream buffer until a newline is output or fflush(stdout). Upon exiting the program, all streams are flushed and closed, hence the 135 appears last in the output.

You can obtain the 123456 output by configuring stdout as unbuffered with setvbuf(stdout, NULL, _IONBF, 0) before writing anything to stdout.

huangapple
  • 本文由 发表于 2023年8月9日 00:15:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定