Reading numbers from a text file into an array in C Reading numbers from a text file into an array in C arrays arrays

Reading numbers from a text file into an array in C


change to

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


5623125698541159 is treated as a single number (out of range of int on most architecture). You need to write numbers in your file as

5 6 2 3 1 2 5  6 9 8 5 4 1 1 5 9  

for 16 numbers.

If your file has input

5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9 

then change %d specifier in your fscanf to %d,.

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

Here is your full code after few modifications:

#include <stdio.h>#include <stdlib.h>int main(){    FILE *myFile;    myFile = fopen("somenumbers.txt", "r");    //read file into array    int numberArray[16];    int i;    if (myFile == NULL){        printf("Error Reading File\n");        exit (0);    }    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]);    }    fclose(myFile);    return 0;}


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

This is attempting to read the whole string, "5623125698541159" into &numArray[0]. You need spaces between the numbers:

5 6 2 3 ...