【问题标题】:random numbers being read into array insted of the text file values随机数被读入数组而不是文本文件值
【发布时间】:2022-11-14 21:29:32
【问题描述】:

我正在尝试创建一个函数,将文本文件中的所有数字读取到一个数组中,其中文件的每一行都有一个数字,例如:

57346
40963
24580
98307
98312
32777
10
16392
16396
...

我的函数确实分配了必要的大小来存储值,但是存储的值是随机值和 0,它们不在我的文本文件中。输出例如:

0
0
296386
0
-485579776
-653048057
584
0
2095946880
...

这是我的代码:

typedef struct set{
    void** values;
    int size; 
}Set;
int checkSize(FILE* file) { 
    int counter = 0;
    char chr;
    chr = getc(file);

    while (chr != EOF) {
        if (chr == '\n') {
            counter = counter + 1;
        }
        chr = getc(file);
    }
    return counter;
}
Set* readSet(FILE* file){ 
    Set* new = malloc(sizeof(Set));
    new->size = checkSize(file);
    new->values = malloc(sizeof(void*)*new->size);
    int arrayAux[new->size];
    int i = 0, n;
    
    while(i < new->size) {
        fscanf(file, "%ld", &arrayAux[i]);
        new->values[i] = arrayAux[i];
        i++;
    }
    
    //loop to remove the first three lines of the file, wich are the number of values in the file,
    //the biggest value of the file and the division between the number of values and the biggest value
    for(i = 0; i < 3; i++) {   
            new->values[i] = new->values[i + 1];
            new->size--;
        }
    for (i = 0; i <= new->size; i++) {
        printf("%d\n", new->values[i]);
    }

    
    return new;
}

我怎样才能解决这个问题?提前感谢您的帮助。

【问题讨论】:

  • 为什么void** 而不是int * 用于values 字段?由于您存储的是 int 值而不是指针。另外,请显示打印结果的代码。也就是说,提供一个完整的minimal reproducible example 来重现问题。
  • 您需要在调用checkSizerewind 文件,因为文件指针将位于文件末尾。
  • checkSize 读取到文件末尾,因此 fscanf 没有任何内容可供读取。检查返回值,以便知道它是成功还是失败。 chr 也应该是 int
  • 在调试期间您应该调查的一件事是问题是否是 (1) 值被正确读取并存储到数组中,但是当您尝试打印它们时出现损坏;或 (2) 从一开始就没有正确读取这些值。这将告诉您需要关注程序的哪一部分。
  • "%ld" 需要一个指向 long 变量的指针。但是您提供的是&amp;arrayAux[i],它是指向int 的指针。

标签: arrays c txt


【解决方案1】:

为什么空而不长?

你不能做 int arrayAux[new->size];因为 size 是一个变量,因此不能在编译时使用!!! 100% 保证读数越界。 将文件中的值读入 long 并将其分配到列表中的适当空间。

为什么每一行都有大小?使用全局整数

为什么要循环跳过列表中的前三个? 大小 -=3 我+=3 效果也一样

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 2021-01-21
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多