【问题标题】:C: Garbage value read into array of intsC:垃圾值读入整数数组
【发布时间】:2014-10-16 23:28:36
【问题描述】:

我查看了 [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 垃圾值从何而来?

【问题讨论】:

  • 您在打印循环中的终止条件错误。应该是while (j &lt; i)

标签: c arrays garbage


【解决方案1】:

int 数组末尾不会有空字符 \0。幸运的是,您有一个变量来跟踪数组的大小-i。您的第二个 while 循环应该有一个如下所示的条件:

while(j<i)

【讨论】:

  • 行得通,谢谢。假设我只想将文件的第一行读入一个数组。我会为此使用 fgets 吗?
猜你喜欢
  • 2013-05-07
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多