0

I looked at [ Read list of numbers in txt file and store to array in C ] to figure out how to read a file of ints into an array.

#include <stdlib.h>
#include <stdio.h>

int second_array[100], third_array[100];

int main(int argc, char *argv[])
{
   int first_array[100]; 
   FILE *fp;

   fp = fopen("/home/ldap/brt2356/435/meeting_times.txt", "r");

   /* Read first line of file into array */
   int i = 0;
   int num;
   while(fscanf(fp, "%d", &num) == 1) {
      first_array[i] = num;
      i++;
   }

   /* Print contents of array */
   int j = 0;
   while(first_array[j] != '\0') {
      printf("%d", first_array[j]);
      j++;
   }
   printf("\n");

   fclose(fp);

   return(0);
}

The file looks like this:

5 3 2 4 1 5
2 2 4
7 9 13 17 6 5 4 3

The array prints out correctly, except at the very end there is a garbage value. An example output looks like this:

5324152247913176543-1216514780

Where is the -1216514780 garbage value coming from?

Community
  • 1
  • 1
BrianRT
  • 1,952
  • 5
  • 18
  • 27
  • 1
    Your termination condition in the print loop is wrong. It should be `while (j < i)`. – ooga Oct 16 '14 at 23:30

1 Answers1

2

An int array is not going to have a null character, \0 at the end. Luckily, you have a variable which keeps track of the size of the array- i. Your second while loop should have a conditional that looks like this:

while(j<i)
Sam12345
  • 91
  • 5
  • That works, thank you. Let's say that I just want to read in the first line of the file into an array. Would I use fgets for that? – BrianRT Oct 16 '14 at 23:36