Reputation: 1962
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?
Upvotes: 0
Views: 612
Reputation: 91
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)
Upvotes: 2