[英]C - printf and scanf buffer
I'm sorry about the generic title, but i didn't find anything better. 我对通用标题感到抱歉,但没有找到更好的选择。 And I'm sorry if the question is stupid but I'm a novice and I could not find anything of use to me.
我很抱歉,如果问题很愚蠢,但我是新手,因此找不到任何有用的方法。
I have written this code to solve a simple problem: you have a sequence of positive integers terminated by a negative: for every integer you have to print a corresponding amount of *
characters and go to a new line. 我已经编写了这段代码来解决一个简单的问题:您有一个以负号结尾的正整数序列:对于每个整数,您都必须打印相应数量的
*
字符并转到新行。
The code DOES WORK but I can't really understand WHY. 该代码可以正常工作,但我无法真正理解为什么。
int main()
{
int d=0,i;
while (d>=0){
scanf("%d",&d);
for (i=0;i<d;i++)
{
printf("*");
}
printf("\n");
}
return 0;
}
I did a bit of research and I understand that terminal gives the integer sequence to scanf
only when I press return. 我做了一些研究,并且了解到终端仅在按回车键时才将整数序列赋予
scanf
。 I thought it would work this way: 我认为这样可以工作:
scanf
gets the integer sequence it registers the first one while the others are discarded scanf
获取整数序列,它注册第一个整数,而其他整数则被丢弃 *
s corresponding to the first integer *
s的数量 Instead it seems that scanf
reads the first integer, then printf sends it to a buffer then the cycle restarts and scanf
gets the second integer and so on. 相反,似乎
scanf
读取了第一个整数,然后printf将其发送到缓冲区,然后循环重新启动, scanf
获取了第二个整数,依此类推。 When the last positive integer is reached printf
flushes the buffer. 当到达最后一个正整数时,
printf
刷新缓冲区。
Am I wrong? 我错了吗? And if not, why does it work this way?
如果没有,为什么它会这样工作?
scanf()
does reads the first integer, then printf sends it to a buffer then the cycle continues and scanf gets the second integer and so on. scanf()
确实读取了第一个整数,然后printf将其发送到缓冲区,然后循环继续 ,scanf获取了第二个整数,依此类推。 After a negative integer is reached the rest of stdin is ignored . 在达到负整数之后 ,其余的stdin将被忽略 。
stdout
is flushed with each \\n
and program ending. 每个
\\n
和程序结尾都将刷新stdout
。
This should clear your ideas about scanf
这应该清除您对
scanf
的想法
http://home.datacomm.ch/t_wolf/tw/c/getting_input.html http://home.datacomm.ch/t_wolf/tw/c/getting_input.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.