[c] Reading numbers from a text file into an array in C

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.

This question is related to c arrays file scanf

The answer is


Loop with %c to read the stream character by character instead of %d.


There are two problems in your code:

  • the return value of scanf must be checked
  • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, j;
    short unsigned digitArray[16];
    i = 0;
    while (
        i != sizeof(digitArray) / sizeof(digitArray[0])
     && 1 == scanf("%1hu", digitArray + i)
    ) {
        i++;
    }
    for (j = 0; j != i; j++) {
        printf("%hu\n", digitArray[j]);
    }
    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 ...

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;
}

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to scanf

How to scanf only integer? Reading numbers from a text file into an array in C How can I read an input string of unknown length? Reading in double values with scanf in c How to do scanf for single char in C printf not printing on console How to find EOF through fscanf? How to read numbers separated by space using scanf Going through a text file line by line in C What is the format specifier for unsigned short int?