c - 如何从文本文件中读取单词并添加到字符串数组中?

标签 c arrays

这是我调用的函数:getWord(words);

void getWord(char words[][MAXWORDLENGTH]){
int i;
char newWord[MAXWORDLENGTH];
FILE* file;
file = fopen("wordbank.txt","r");
if(file==NULL){
    printf("Error\n");
}else{
    printf("File read\n");
    for(i=0;i<=MAXWORDS;i++){
        fgets(newWord, "%s", file);
        printf("newWord: %s", newWord);
        strcpy(words[i], newWord);
    }

}
fclose(file);

不幸的是,我的数组“words”没有用字符串填充每个元素,它能够将我的文本文件中的第一个单词捕获到 [0] 元素中,然后剩下的就是乱码。

我的文本文件如下所示:

apple
winter
summer
skunk
clouds
pencil
grape

我使用指针而不是数组会更容易吗?

感谢您的帮助!

最佳答案

好吧,你可能让事情变得比他们需要的更困难。该评论并不是要挑剔您,但是无论您使用的是什么编译器/IDE,都应该左右吐出错误。它编译的事实令人惊讶。评论中的建议是合理的。始终,始终在启用警告的情况下进行编译,并在您认为您的代码值得信赖之前修复所有警告。

话虽这么说,但您在某些方面让自己变得很困难。您应该传递数组和 FILE* 指针(或文件名),而不是在函数中对文件名进行硬编码。这使得该功能的用途非常有限。正如您现在所知,您对 fgets 的使用是不正确的。此外,在传递数组后,您只需将每个单词(假设每行 1 个)读入数组,同时确保不超过声明的行数。

这是一个简短的示例,它将从命令行中给出的文件名中读取(或者默认情况下从 stdin 中读取)。它使用 三元 运算符来接受文件名作为第一个参数或将 fp 设置为 stdin。试一试,如果您有任何问题,请告诉我:

#include <stdio.h>

#define MAXW 64  /* maximum number of lines to read */
#define MAXC 32  /* longest word in abridged Dict. is 28 char
                    "Antidisestablishmentarianism"  */

size_t getwords (char (*words)[MAXC], FILE *fp);

int main (int argc, char **argv) {

    char words [MAXW][MAXC] = {{0}};    /* array to hold words  */
    size_t nwords = 0;                  /* number of words read */
    size_t i;

    /* open argv[1] for reading (default: stdin) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    nwords = getwords (words, fp);

    if (fp != stdin) fclose (fp);   /* close file */

    printf ("\n words read from '%s':\n\n",
            argc > 1 ? argv[1] : "stdin");
    for (i = 0; i < nwords; i++)
        printf ("  words[%2zu] : %s", i, words[i]);

    return 0;
}

/* function to read words, 1 - per line, from 'fp' */
size_t getwords (char (*words)[MAXC], FILE *fp)
{
    size_t idx = 0;                     /* index of words read */

    /* read each line in file into words array
       note: includes trailing newline character */
    while (idx < MAXW && fgets (words[idx], MAXC, fp)) {
        idx++;
        /* note you should check if chars remain in line */
    }

    if (idx == MAXW)   /* check word count against MAXW */
        fprintf (stderr, "warning: MAXW words read.\n");

    return idx;
}

编译

gcc -Wall -Wextra -O3 -o bin/fgets_array_words_fn fgets_array_words_fn.c

输入文件

$ cat dat/captnjack1.txt
This
is
a
tale
Of
Captain
Jack
Sparrow
A
Pirate
So
Brave
On
the
Seven
Seas.

输出

$ ./bin/fgets_array_words_fn dat/captnjack1.txt

 words read from 'dat/captnjack1.txt':

  words[ 0] : This
  words[ 1] : is
  words[ 2] : a
  words[ 3] : tale
  words[ 4] : Of
  words[ 5] : Captain
  words[ 6] : Jack
  words[ 7] : Sparrow
  words[ 8] : A
  words[ 9] : Pirate
  words[10] : So
  words[11] : Brave
  words[12] : On
  words[13] : the
  words[14] : Seven
  words[15] : Seas.

或者从stdin读取:

$ ./bin/fgets_array_words_fn <dat/captnjack1.txt

 words read from 'stdin':

  words[ 0] : This
  words[ 1] : is
  ...

关于c - 如何从文本文件中读取单词并添加到字符串数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34149140/

相关文章:

java - 通过输入与数据关联的名称来查找数据

c++ - C/C++ 分配类似对象的数组数组

python - python ECDSA 和 C micro-ecc 库之间的 ECDSA 签名和验证问题

c - 使用 C 程序从 txt 文件中读取坐标

c - 如何使用C从PID中获取进程名称

arrays - C# : UDP Socket - Receive data with unknown size

c# - 我如何识别代表 SZ-Array 的 System.Type 实例?

c - 如何从带有指针的函数返回数组

c - 并发标志集是否需要#pragma omp atomic?

c - 将 long 和 time_t 的大小定义为 4bytes