Search code examples
cinputgetchar

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


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()?


Solution

  • 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