繁体   English   中英

如何将文件中的单词存储到动态字符串数组中?

[英]how to store words from a file to a dynamic array of strings?

我正在尝试存储文件中的数据(逐行单词)最大长度为 16

当我运行代码时,它只存储文件中的最后一个单词并打印它(文件中所有单词的数量)次。

如果文件包含 10 个单词,最后一个单词是 test,则 output 被测试 10 次

当我尝试 while 循环扫描文件时,我得到了垃圾数据

这是我的代码

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



int main()
{
    FILE *file;

    file = fopen("words.txt", "r");

    char word[20];
    int words_count=0; // count the words in the file

    while (fscanf(file, "%s", word) != EOF)
    {
        words_count++;
    }

    printf("%d", words_count); // i get the right number of words in the file at this step


    char **list_of_words = malloc (words_count * sizeof(char *)); //allocate memory to store enough pointers to charecters

    int length;

    for (int i=0; i<words_count; i++)
        {
            fscanf(file, "%s", word);
            length = strlen(word);
            word[length+1] = '\0';
            list_of_words[i] = malloc (length+1 * sizeof(char)); //allocate memory for each word 
            list_of_words[i] = word;  //I used strcpy(), but I got the same output 
        }



    for (int i=0; i<words_count; i++)
    {
        printf("%s\n", list_of_words[i]); //print the words 
    }


    fclose(file);
}

有几个问题:

  • 一旦你阅读了文件,你就到了文件的末尾。 如果要再次读取文件,需要再次将文件指针移到文件的开头。
  • 你肯定需要在这里使用strcpylist_of_words[i] = word是没有意义的,你想要复制字符串,而不是用指向局部变量的指针覆盖之前分配的指针(试试看会发生什么)。
  • length+1 * sizeof(char)是错误的,您打算(length + 1) * sizeof(char) 然而,偶然的是,这两个表达式给出了相同的结果。 所以在这种特殊情况下这不会导致错误。 但无论如何length+1就足够了,因为sizeof(char)根据定义为 1。
  • word[lengt+1] = '\0'是无用的,因为在fscanf之后word[length+1]根据定义为 0。 但这不会导致错误。
  ...
  fseek(file, SEEK_SET, 0);               // rewind the file so you can read it 
                                          // again
  for (int i = 0; i < words_count; i++)
  {
    fscanf(file, "%s", word);
    length = strlen(word);
//    word[length + 1] = '\0';            // remove this, it's useless
    list_of_words[i] = malloc(length + 1); // remove the sizeof(char)  which is 1 by definition
    strcpy(list_of_words[i], word);       // use strcpy
  }
  ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM