繁体   English   中英

如何使用 fscanf 读取包含多个单词的文本文件并通过索引将它们存储到字符串数组中

[英]How to use fscanf to read a text file including many words and store them into a string array by index

wordlist.txt 包括:

able
army
bird
boring
sing
song

我想使用 fscanf() 逐行读取这个 txt 文件,并通过索引每个单词将它们存储到一个字符串数组中,如下所示:

src = [able army bird boring sing song]

其中 src[0]= "able", src[1] = "army" 等等。 但我的代码只输出 src[0] = "a", src[1] = "b" ... 有人能帮我弄清楚我的代码出了什么问题:

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

int main(int argc, char *argv[])
{
    FILE *fp = fopen("wordlist.txt", "r");
    if (fp == NULL)
    {
        printf("%s", "File open error");
        return 0;
    }
    char src[1000];
    for (int i = 0; i < sizeof(src); i++)
    {
        fscanf(fp, "%[^EOF]", &src[i]);
    }
    fclose(fp);
    printf("%c", src[0]);
    getchar();
    return 0;
}

相当赞赏!

例如像这样。

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

#define MAX_ARRAY_SIZE 1000
#define MAX_STRING_SIZE 100

int main(int argc, char *argv[]) {
    FILE *fp = fopen("wordlist.txt", "r");
    if (fp == NULL) {
        printf("File open error\n");
        return 1;
    }
    char arr[MAX_ARRAY_SIZE][MAX_STRING_SIZE];
    int index = 0;
    while (1) {
        int ret = fscanf(fp, "%s", arr[index]);
        if (ret == EOF) break;
        ++index;
        if (index == MAX_ARRAY_SIZE) break;
    }
    fclose(fp);
    for (int i = 0; i < index; ++i) {
        printf("%s\n", arr[i]);
    }
    getchar();
    return 0;
}

一些注意事项:

  • 如果有错误,最好返回 1 而不是 0,因为 0 表示执行成功。
  • 对于字符数组,您使用指针。 对于字符串数组,您使用双指针。 习惯它们有点棘手,但它们很方便。
  • 此外,检查 fscanf 的返回值会很棒。
  • 对于固定大小的数组,使用#define定义大小很有用,以便以后在代码中多次使用时更容易更改。

它一次读取一个字符,它本身的大小为 4,就像我们在 word 中看到的 sizeof('a') 一样。 'b' 等也是如此。 因此,您可以使用的一种方法是不断检查何时有空格或换行符,以便我们可以将这两件事之前的数据保存为一个单词,然后通过在它们之间添加空格并将它们连接起来来组合这些小数组以获得单个大批。

暂无
暂无

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

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