首页 > 解决方案 > 我正在尝试将文件中的字符串列表存储到 C 中的数组中

问题描述

我正在尝试读取包含单词列表的文件并将它们存储在数组中。存储后,我随机尝试打印第 10 个元素以确保代码完成了它应该做的事情,但我没有成功。我还收到以下警告,但我不明白它在告诉我什么:

警告:从 'char *' 对 'char' 的赋值使指针变成整数而无需强制转换 [-Wint-conversion] 22 | dict[i][j]=word_scanned;

#include <stdio.h>

#include <stdlib.h>

int main() {

    char word_scanned[50];

    char dict[102402][50];

    int i,j;

    FILE *fptr;

    if ((fptr = fopen("/usr/share/dict/words", "r")) == NULL) {

        printf("Error! opening file\n");

        // Program exits if file pointer returns NULL.

        exit(1);

    }


   for(i=0; !feof(fptr); i++){

        fscanf(fptr,"%s", word_scanned);

       for (j=0; j<50; j++){

            dict[i][j]=word_scanned;  

       }

   }

    printf("%s\n",dict[9]);

    fclose(fptr);

    return 0;  
}

标签: carraysstringfilechar

解决方案


dict[i][j]=word_scanned[j];是答案。

但也阅读了有关 strncpy 的信息,而且仅供参考fscanf(fptr,"%s", word_scanned);并不比直接扫描更安全,fscanf(fptr,"%s", dict[i]);因为 word_scanned 也是 50 字节长。任何超过 50 个字符的字符串都会导致内存错误,因此这个额外的缓冲区根本没有帮助。


推荐阅读