Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading numbers from a text file into an array in C

Tags:

arrays

c

file

scanf

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.

like image 778
Vonti Avatar asked Dec 04 '13 14:12

Vonti


People also ask

How do you read an array of text files in C++?

Use fstream to Read Text File Into 2-D Array in C++ To read our input text file into a 2-D array in C++, we will use the ifstream function. It will help us read the individual data using the extraction operator. Include the #include<fstream> standard library before using ifstream .


2 Answers

change to

fscanf(myFile, "%1d", &numberArray[i]); 
like image 184
BLUEPIXY Avatar answered Oct 25 '22 17:10

BLUEPIXY


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; } 
like image 30
haccks Avatar answered Oct 25 '22 16:10

haccks