我看了 [ Read list of numbers in txt file and store to array in C ] 来弄清楚如何将整数文件读入数组。
#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);
}
文件看起来像这样:
5 3 2 4 1 5
2 2 4
7 9 13 17 6 5 4 3
数组打印正确,除了最后有一个垃圾值。示例输出如下所示:
5324152247913176543-1216514780
-1216514780 垃圾值从何而来?
最佳答案
int
数组不会有空字符,\0
在末尾。幸运的是,您有一个变量可以跟踪数组的大小 - i
。你的第二个 while 循环应该有一个如下所示的条件:
while(j<i)
关于C:读入整数数组的垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26415565/