Why do i have to press ctrl+d several times for sc

2019-08-30 19:29发布

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).

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

My code :

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;
   }; 
 };
};

标签: c scanf eof
1条回答
Viruses.
2楼-- · 2019-08-30 19:51

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.

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.

查看更多
登录 后发表回答