Inputting issues with while(scanf): why does using getchar() keep the input going

StackOverflow https://stackoverflow.com/questions/23320772

  •  10-07-2023
  •  | 
  •  

I am trying to take 8 inputs through the while(scanf) process. At first, I tried the following piece of code :

while(scanf("Dia %d %d : %d : %d Dia %d %d : %d : %d",&day_start,&h1,&m1,&s1,&day_end,&h2,&m2,&s2)==8)    

But, after one execution of the program, it terminates. Then, I used a getchar() after the input, like the following:

while(scanf("Dia %d %d : %d : %d Dia %d %d : %d : %d",&day_start,&h1,&m1,&s1,&day_end,&h2,&m2,&s2)==8)
{
    getchar();
    ......;
}

After doing this, the input kept going on after every execution. So, why does using getchar() keep the input going?

Is it because, the last enter was taken as an input and after using getchar(), the enter was taken in the getchar()?

有帮助吗?

解决方案 2

In this piece of code

while(scanf("Dia %d %d : %d : %d Dia %d %d : %d : %d",&day_start,&h1,&m1,&s1,&day_end,&h2,&m2,&s2)==8)

after the first execution the last enter-key pressed is taken as the first character of the second scanf which it must be D to continue, and this can't be reached.

while in this piece of code

while(scanf("Dia %d %d : %d : %d Dia %d %d : %d : %d",&day_start,&h1,&m1,&s1,&day_end,&h2,&m2,&s2)==8)
{
    getchar();
    ......;
}

the last enter-key goes to getchar() not to scanf

其他提示

On the topic of scanf...

http://www.giannistsakiris.com/2008/02/07/scanf-and-why-you-should-avoid-using-it/

Now what specifically is happening when you used getChar? Do you mean it reaches an infinite loop, or it passes through the while loop and "keeps on going"?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top