为什么我必须多次按ctrl + d才能使scanf看到它? [英] Why do i have to press ctrl+d several times for scanf to see it?
问题描述
在我的程序中,我需要以这种格式读取数字-数字,数字,数字等,并且在用户按ctrl + d时结束。我切换 scanf(%d,& i)
和 scanf(%c,& c)
。
in my program i need to read numbers in this format - number, number, number etc., and it ends when user press ctrl+d. I switch scanf("%d",&i)
and scanf("%c",&c)
.
我的问题是,该程序结束,当我按ctrl + d 3次时,由于某种原因,第一次和第二次它都将其忽略。我还注意到,如果我调试并写入: 5、6ctrl + d,它将读取 5,然后等待下一个输入。为什么,当已经有6并且ctlr + d时?谢谢
My problem is, that the program ends, when i press ctrl+d 3 times, the first and second time it ignores it for some reason. I also noticed, that if i debug and write : " 5, 6ctrl+d " it reads " 5, " and then it waits for next input. Why, when there is 6 and ctlr+d already ? Thanks
我的代码:
for (;;)
{
if (cislo==1)
{
res=scanf("%d",&matice[x][y]);
if (res==-1)
{
...
return 1; /* i want EOF to be after number, not char */
} else
{
...
cislo=0;
}
} else
{
res=scanf("%c",&znak);
if (res==-1)
{
...
break;
} else
{
...
cislo=1;
};
};
};
推荐答案
您正在尝试读取3个输入,其中3个 scanfs()
,每个 CTRL-D
被视为一个输入,因此您的程序将忽略前两个,并在第3个之后终止。
You are trying to read 3 inputs with 3 scanfs()
, each CTRL-D
treated as one input, hence your program ignores initial two and terminates after 3rd.
对于像 5、6ctrl + d
这样的输入, scanf()
读取整个字符串,但仅将 5
转换为适当的数字并将其存储在提供的变量中。之后的字符串将被丢弃。再下一个 scanf()
等待读取下一个数字。
For input like 5, 6ctrl+d
, the scanf()
reads entire string, but only converts 5
to appropriate number and stores in provided variable. The string after that is discarded. Again next scanf()
waits to read next number.
这篇关于为什么我必须多次按ctrl + d才能使scanf看到它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!