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

时间:2021-12-16 19:58:03

Here is my function which is called with:getWord(words);

这是我的函数调用: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);

}

}

Unfortunately my array "words" does not fill each element with a string, it is able to capture the first word in my text file into the [0] element and then the rest is gibberish.

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

my text file looks like this:

我的文本文件如下所示:

apple
winter
summer
skunk
clouds
pencil
grape

Would it be easier for me to use a pointer instead of an array?

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

Thanks for the help!

谢谢您的帮助!

2 个解决方案

#1


2  

Alright, you may be making things more difficult than they need to be. The comment wasn't meant to pick on you, but whatever compiler/IDE you are using should have been spitting out ERRORS right and left. The fact that it compiled at all is surprising. The advise in the comment was sound. Always, always compile with warnings enabled and fix all warnings before you consider your code trustworthy.

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

That being said, you have a couple of areas where you are making things hard on yourself. You should pass the array, and a FILE* pointer (or filename) rather than hardcoding a filename in a function. That makes the function of very limited use. Your use of fgets, as you now know, was not correct. Further, after you pass your array, you need only read each word (assuming 1-per line) into the array while making sure your don't exceed the number of rows you have declared.

话虽这么说,你有几个方面,你自己在努力。您应该传递数组和FILE *指针(或文件名),而不是在函数中硬编码文件名。这使得使用非常有限。正如您现在所知,您对fgets的使用并不正确。此外,在传递数组后,您只需要读取每个单词(假设每行1个),同时确保不超过您声明的行数。

Here is a short example that will read from the filename given on the command line (or from stdin by default). It makes use of a ternary operator to either accept a filename as the first argument or set fp to stdin. Give it a try and let me know if you have questions:

这是一个简短的示例,它将从命令行(或默认情况下从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;
}

Compile

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

Input File

输入文件

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

Output

产量

$ ./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.

or reading from stdin:

或者从stdin读取:

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

 words read from 'stdin':

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

#2


0  

Use fread() method

使用fread()方法

while(fread(newWord, MAXWORDLENGTH,1,file)){
    printf("newWord: %s", newWord);
    strcpy(words[i], newWord);
}

#1


2  

Alright, you may be making things more difficult than they need to be. The comment wasn't meant to pick on you, but whatever compiler/IDE you are using should have been spitting out ERRORS right and left. The fact that it compiled at all is surprising. The advise in the comment was sound. Always, always compile with warnings enabled and fix all warnings before you consider your code trustworthy.

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

That being said, you have a couple of areas where you are making things hard on yourself. You should pass the array, and a FILE* pointer (or filename) rather than hardcoding a filename in a function. That makes the function of very limited use. Your use of fgets, as you now know, was not correct. Further, after you pass your array, you need only read each word (assuming 1-per line) into the array while making sure your don't exceed the number of rows you have declared.

话虽这么说,你有几个方面,你自己在努力。您应该传递数组和FILE *指针(或文件名),而不是在函数中硬编码文件名。这使得使用非常有限。正如您现在所知,您对fgets的使用并不正确。此外,在传递数组后,您只需要读取每个单词(假设每行1个),同时确保不超过您声明的行数。

Here is a short example that will read from the filename given on the command line (or from stdin by default). It makes use of a ternary operator to either accept a filename as the first argument or set fp to stdin. Give it a try and let me know if you have questions:

这是一个简短的示例,它将从命令行(或默认情况下从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;
}

Compile

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

Input File

输入文件

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

Output

产量

$ ./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.

or reading from stdin:

或者从stdin读取:

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

 words read from 'stdin':

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

#2


0  

Use fread() method

使用fread()方法

while(fread(newWord, MAXWORDLENGTH,1,file)){
    printf("newWord: %s", newWord);
    strcpy(words[i], newWord);
}