无法用 C 中的文本文件中的数据填充数组

标签 c arrays

我有一个名为 proj3input.dat 的数据文件,它有 10000 个条目,我必须使用这些条目来填充一个数组。我无法将文件中的数据放入数组中。这段代码(对于丑陋的格式感到抱歉,它完全改变了我粘贴到 stackoverflow 中)当前打印一个全是 0 的数组,我看不出我的错误在哪里。数据点都是小数,不是整数,现在我只需要获取数据点来填充我的数组 data[10000]。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define MAX_FILE_NAME 100

int main(int argc, char *argv[])
{
  FILE *proj3input, *output;
  int i, count = 0, max_window, window_size, p, m, q, x;
  int *num_windows;
  double time[10000], data[10000], data_mean, data_sum;
  char filename[MAX_FILE_NAME];
  char c;

  /* Open files */
  proj3input = fopen("proj3input.txt", "r");
  output = fopen("output.dat", "w"); /* prototype any functions! */

  /*Verify file*/
  if (proj3input == (FILE *)NULL) {
    printf("**********ERROR**********\n");
    printf("* Cannot open required  *\n");
    printf("*  file. Please check   *\n");
    printf("*    your directory     *\n");
    printf("**********ERROR**********\n");
    exit(EXIT_FAILURE);
  }

  for (c = getc(proj3input); c != EOF; c = getc(proj3input)) {
    if (c == '\n') {
      count = count + 1;
    }
  }
  printf("The file has %d lines \n", count);
  max_window = count;
  printf("Please enter the size of the window you require.\n");
  printf("This must be an integer greater than 1 and less than %d\n",
         max_window);
  scanf("%d", &window_size);

  /* If validation failed ... */
  /*if(!validInput)
  {
     printf(" ERROR: No input detected. Please input a positive integer. \n");
     return(EXIT_FAILURE);
     }*/

  /* Here we check that we have a valid window size*/
  if (window_size == 0) {

    printf("**********ERROR**********\n");
    printf("*  Input value must be  *\n");
    printf("*  nonzero. Please run  *\n");
    printf("*  again with non zero  *\n");
    printf("*        input          *\n");
    printf("**********ERROR**********\n");
  }

  if (num_windows == NULL) {
    printf("Memory allocation failure. Exiting...\n");
    return (EXIT_FAILURE);
  }

  for (i = 0; i <= 10000; i++) {
    fscanf(proj3input, "%lf", &data[i]);
  }

  /* Close the file */
  fclose(proj3input);

  for (x = 0; x < 10; x++) {
    printf("%lf\n", data[x]);
  }

  return 0;
}

最佳答案

用于计算读取整个文件的行数的循环:

for(c= getc(proj3input); c != EOF; c = getc(proj3input)){
    if(c == '\n'){
        count = count + 1; 
        }
}

所以当你再去读它的时候,你已经到了文件的末尾,无法继续阅读了。您需要在初始行数之后添加一个 rewind 调用:

rewind(proj3input);

关于无法用 C 中的文本文件中的数据填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27889248/

相关文章:

c - 在 Ansi-C 中导入 Delphi Dll

C 指针(使用指针时 int 和 char 之间的区别),示例如下?

javascript - Console.log 将数组转换为逗号分隔值

c++ - 在cpp中初始化数组并用零填充

javascript - 如何在中间停止 For 循环并从那里继续返回 JavaScript

c - 跳出内联汇编在 AVR32 上转到了错误的目标

我们可以在 C 语言中将整数值转换为指针类型吗?

c - 如何一次将数组中的数字复制到二进制文件中?

c - 在 C 中查找总内存(以字节为单位)

mysql - 在循环中将数组值更多列插入到mysql