【问题标题】:Retrieving an array from a file and find it's size C从文件中检索数组并找到它的大小 C
【发布时间】:2017-04-14 04:05:42
【问题描述】:

我有一个文件,我必须从中读取一些数字并将它们放入一个数组中。唯一的问题是我不知道如何找到它的大小。我得到了数组的最大大小,但数字并没有完全填满数组。我尝试了许多不同的方法来使其工作,但它没有从文件中读取正确的值。没有sizeof还有其他方法吗?

#include<stdio.h>

#define MAX_NUMBER 25
int main(void)
{
int test[];
int size;

FILE* sp_input;    
int i;
sp_input = fopen("a20.dat", "r");

if (sp_input == NULL)
  printf("\nUnable to open the file a20.dat\n");
else
  {
  while( fscanf(sp_input, "%d", &test[i])!=EOF)
  {
  size=sizeof(test)/sizeof(test[0]);
  }

    for(i = 0; i < size; i++)

  printf("\na[%d]=%d has a size of %d\n", i,test[i],size);
  fclose(sp_input);    
  }

  return 0; 
}

【问题讨论】:

  • i 未初始化,并且永远不会更改您的 while 循环中的值。
  • 如果size 应该是数组中有多少个数字,为​​什么不直接从 0 开始,并为读取的每个数字递增?
  • 另外,您需要提供test 的元素数量,例如。 int test[MAX_NUMBER]; -- 数组总是有最大数量的元素,但是您可以使用 size 跟踪您实际使用的元素数量。
  • 这一行:int test[]; 无法编译!建议:`int test[ MAX_NUMBER ];
  • 这一行:while( fscanf(sp_input, "%d", &amp;test[i])!=EOF) 正在使用变量i 而没有初始化它,因此它包含了堆栈上i 位置处内存中的垃圾。并且i 没有递增以遍历数组test[] 建议:i = 0; while( i&lt;MAX_NUMBER &amp;&amp; 1 == fscanf(sp_input, "%d", &amp;test[i]) ) i++;

标签: c arrays sizeof maxlength


【解决方案1】:

如果每次成功执行fscanf 时增加i,它将作为读取项目数的计数。

i = 0;

while (fscanf(sp_input, "%d", &test[i]) == 1) {
    i = i + 1;
}

// Now, i is the number of items in the list, and test[0] .. test[i-1]
// are the items.

编辑:正如@chux 指出的那样,在这种情况下,最好在每次调用时与预期的扫描项目数 1 进行比较。如果提供了虚假输入(非数字),仍然存在问题,您应该停止。

【讨论】:

  • 次要 fscanf(sp_input, "%d", &amp;test[i]) == 1 更惯用,因为只要结果符合预期,循环就会继续,而不是其他可能的 fscanf() 结果之一。当然,在这种情况下,只需要 EOF 或 1,但这个公理适用于更复杂的扫描。
【解决方案2】:

定义一个最大尺寸的数组并尽可能继续循环。

文件输入不需要填充数组,只需尽可能填充它即可。跟踪i 使用了多少test[],并确保不要过度填充数组。

#define MAX_NUMBER 25
int test[MAX_NUMBER];

FILE* sp_input = fopen("a20.dat", "r");
...

// Use `size_t` for array indexing    
size_t i;
// do not read too many `int`    
for (i=0; i<MAX_NUMBER; i++) {
  if (fscanf(sp_input, "%d", &test[i]) != 1) {
    break;
  }
  printf("test[%zu]=%d\n", i, test[i]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2015-04-15
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    相关资源
    最近更新 更多