0

I wonder why scanf wants to get one more than the number of 'num' when I use this function for array index with infinite loop.

5 // The number of the index of an array.

1 2 3 4 5 // I put 5 numbers because I set the number of the index as 5. but..

6 // I had to put another number to finish the work of scanf.

1 2 3 4 5 // The numbers in the array. 6 has disappeared.

Here is a code that I made to test.

#include <stdio.h>

int main()
{
    int num = 0;
    int n[100000] = { 0 };

    while (1) {
        scanf("%d ", &num);     

        if (num > 100000 || num <= 0) {
            printf("Input a number again. \n");
        }

        else {
            for (int i = 0; i < num; i++) {
                scanf("%d ", &n[i]);
            }

            // Test
            for (int k = 0; k < num; k++) {
                printf("%d ", n[k]);
            }

            break;
        }
    }

    return 0;
}
Community
  • 1
  • 1

2 Answers2

0

I am not sure, but I think that the problem is resulted from the additional space character you added it after the %d in scanf function. Try to remove that space character and see the output.

Maged Saeed
  • 1,784
  • 2
  • 16
  • 35
0

The problem is with your scanf, remove the additional whitespace after %d and it will run fine. Go through this link for further details.