Reading numbers from a text file into an array in C

Vonti picture Vonti · Dec 4, 2013 · Viewed 257.4k times · Source

I'm a programming noob so please bear with me.

I'm trying to read numbers from a text file into an array. The text file, "somenumbers.txt" simply holds 16 numbers as so "5623125698541159".

#include <stdio.h>
main()
{

    FILE *myFile;
    myFile = fopen("somenumbers.txt", "r");

    //read file into array
    int numberArray[16];
    int i;

    for (i = 0; i < 16; i++)
    {
        fscanf(myFile, "%d", &numberArray[i]);
    }

    for (i = 0; i < 16; i++)
    {
        printf("Number is: %d\n\n", numberArray[i]);
    }


}

The program doesn't work. It compiles but outputs:

Number is: -104204697

Number is: 0

Number is: 4200704

Number is: 2686672

Number is: 2686728

Number is: 2686916

Number is: 2004716757

Number is: 1321049414

Number is: -2

Number is: 2004619618

Number is: 2004966340

Number is: 4200704

Number is: 2686868

Number is: 4200798

Number is: 4200704

Number is: 8727656

Process returned 20 (0x14) execution time : 0.118 s Press any key to continue.

Answer

BLUEPIXY picture BLUEPIXY · Dec 4, 2013

change to

fscanf(myFile, "%1d", &numberArray[i]);