将数据从文件放入C中的数组 [英] Put data from file to array in C

查看:211
本文介绍了将数据从文件放入C中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.

#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;
}

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

I am trying to read some data from a text file and store it into an array. Everything is fine while I'm in the loop, but when I get out of there, any value of any index in my array is filled with the last word of the file. Could anyone help me find out mistakes I am doing?

数据文件:

Hello there, this is a new file.

结果:

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

任何帮助将不胜感激!

推荐答案

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

There are atleast 2 points of concern in your code. char word[9999], *arrayOfWords[9999]; defines arrayOfWords to be an array of 9999 char pointers. This is one point of concern.

另一点是arrayOfWords[wordCount] = word;.在这里存储新读取的单词,您需要分配空间,因为arrayOfWords是指针数组.请按如下所示找到修改后的代码.

Another point is arrayOfWords[wordCount] = word;. Here to store the newly read word, you need to allocate space as arrayOfWords is an array of pointers. Please find your modified code as below.

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;
}

这篇关于将数据从文件放入C中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆