Scanf running under a for loop

I have a question about how a for loop works in C. Note the following code:

#include<stdio.h>

void main()
{
    int ar[10],i;
    printf("Enter 10 numbers:");
    for(i=0;i<10;i++)
        scanf("%d",&ar[i]);
    for(i=0;i<10;i++)
        printf("%d",ar[i]);
}

      

When I execute this and give the following input:

1 2 3 4 5 6 7 8 9 10 11 12

      

I gave 12 inputs, but the loop only had to run 10 times (scanf loop). I can give even more resources and he is happy to accept it if I don’t find the enter key. Is there something about the loop that I'm missing here?

+3


source to share


1 answer


Perhaps the following program can help you understand what's going on:

#include<stdio.h>

int main(void)
{
    int ar[10], br[2], i;
    printf("Enter 12 numbers: ");
    fflush(stdout);

    for( i = 0; i < 10; ++i ) {
        scanf("%d", &ar[i]);
    }

    printf("We've read the first 10, let print them...\n");

    for( i = 0; i < 10; ++i ) {
        printf("%d ", ar[i]);
    }

    printf("\nNow, let read the last 2...\n");

    for( i = 0; i < 2; ++i ) {
        scanf("%d", &br[i]);
    }

    printf("We've read the last 2, let print them...\n");

    for( i = 0; i < 2; ++i ) {
        printf("%d ", br[i]);
    }

    putchar('\n');

    return 0;
}

      

which outputs:

paul@local:~/Documents/src/sandbox$ ./scanning
Enter 12 numbers: 1 2 3 4 5 6 7 8 9 10 11 12
We've read the first 10, let print them...
1 2 3 4 5 6 7 8 9 10 
Now, let read the last 2...
We've read the last 2, let print them...
11 12 
paul@local:~/Documents/src/sandbox$ 

      



As you will see, after reading the first ten, the last two numbers are still in the input buffer, and we can read them in a separate loop without asking for more input. In this case, all inputs are made after the end of the first call scanf()

. The program can simply keep reading whatever is in the input buffer without ever having to press another key.

What's wrong with your program is that you just came back from main()

and walked away without even trying to read those last two numbers you enter. This sample program shows that they are still there for reading, however.

If you run the sample program, but you enter less than 12 numbers, then at some point the input will be exhausted, but it scanf()

will stop and wait until you start using it.

+1


source







All Articles