英文:
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] == '%')
{
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);
}
I was expecting 1234567 but the output came out as 2467135
答案1
得分: 2
ft_printf、printf和write的输出不会按照源代码的顺序显示,这是因为缓冲机制的存在:默认情况下,stdout对终端是行缓冲的,这意味着数字1、3和5会被存储在输出流缓冲区中,直到输出换行符或者调用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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论