【问题标题】:Put data from file to array in C将数据从文件放入C中的数组
【发布时间】:2013-02-18 16:17:02
【问题描述】:

这是我的代码。

#include <stdlib.h>
#include <stdio.h>

int main() {
    //Vars
    FILE *fp;
    char word[9999],
        *arrayOfWords[9999];
    int wordCount = 0, i;
    //Actions
    fp = fopen("data.txt", "r");
    if(fp != NULL) {
        while(!feof(fp)) {
            fscanf(fp, "%s", word);
            arrayOfWords[wordCount] = word;
            wordCount++;
        }
        for(i = 0; i < wordCount; i++) {
            printf("%s \n", arrayOfWords[i]);
        }
    puts("");
    } else {
        puts("Cannot read the file!");
    }
    return 0;
}

我正在尝试从文本文件中读取一些数据并将其存储到数组中。 当我在循环中时一切都很好,但是当我离开那里时,我数组中任何索引的任何值都被文件的最后一个单词填充。谁能帮我找出我正在做的错误?

数据文件:

Hello there, this is a new file.

结果:

file.
file.
file.
file.
file.
file.
file.
file.

任何帮助将不胜感激!

【问题讨论】:

    标签: c arrays file


    【解决方案1】:

    您需要为数组的每个单独成员分配内存(使用 malloc 或通过提供数组的第二维并将其声明为 char 类型而不是 char*)。你所做的类似于:

    char *s;
    scanf("%s", s);
    

    这在C 中不起作用。实际上这里你有UB(未定义的行为),因为指针没有初始化。

    编辑:您让数组中的所有字段都指向您的数组word,一旦您读取了单词,您应该为字符串分配新内存,然后将strcpyword 放入其中。

    【讨论】:

    • 我刚刚意识到我粘贴了错误的代码。已编辑。但我想它仍然是一样的。我只是不明白为什么数组的每个索引在循环中都有正确的值。
    • 我已经编辑了你的答案,现在我知道为什么所有字段都具有相同的值 - 它们实际上都指向 word,这也解释了为什么它们都存储最后读取的值。试试看 - 修改 word 并检查所有值是否也发生了变化。
    【解决方案2】:

    您的代码中至少有两点需要关注。 char word[9999], *arrayOfWords[9999];arrayOfWords 定义为 9999 char pointers 的数组。这是一个值得关注的问题。

    还有一点是arrayOfWords[wordCount] = word;。这里要存储新读取的字,您需要分配空间,因为arrayOfWords 是一个指针数组。请在下面找到您修改后的代码。

    int main() {
    //Vars
    FILE *fp;
    char arrayOfWords[30];
    int wordCount = 0, i;
    //Actions
    fp = fopen("data.txt", "r");
    if(fp != NULL) {
        while(!feof(fp)) {
            fscanf(fp, "%s", &arrayOfWords[wordCount]);
            wordCount++;
        }
        puts("");
        for(i = 0; i < (wordCount - 1); i++) {
            puts(arrayOfWords[i]);
        }
    puts("");
    } else {
        puts("Cannot read the file!");
    }
    return 0;
    }
    

    【讨论】:

      【解决方案3】:

      这个:

      arrayOfWords[wordCount] = word;
      

      不会将当前单词复制到单独的存储中,它只是分配另一个指针指向word 所做的同一块存储。所以你最终会得到一个指向同一个word 数组的指针数组。您需要为每个单词单独分配内存并复制组成每个单词的字符(以及 NULL 终止符),而不是指针。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多