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?

1
  • 1
    Your termination condition in the print loop is wrong. It should be while (j < i). Commented Oct 16, 2014 at 23:30

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.