为什么我不能在此代码中使用定界符正确提取令牌?

问题描述 投票:0回答:1

我正在编写代码以从.txt文件中提取所有单词,但是遇到了麻烦。我只允许使用字母和撇号,因此我选择了定界符。这是我的代码:

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


int main()
{
    const char *separators =
    "\n\r !\"#$%&()*+,-./0123456789:;<=>?@[\\]^_`{|}~";
    size_t len = 1000;
    char *word2 = (char *)malloc(len);
    FILE *file2 = fopen("words.txt", "r");
    if (file2 == 0)
    {
        fprintf(stderr, "Failed to open second file for reading\n");
        exit(EXIT_FAILURE);
    }
    while (fgets(word2, sizeof(word2), file2))
    {
        char *token = (char*)strtok(word2, separators);
        while (token != NULL)
        {
            printf("%s", token);
            printf("\n");
            token = strtok(NULL, separators);
        }
    }

    return 0;
}

这是words.txt中的内容:

This is a sentence in the file

我的输出最终是

This
is
a
sent
ence
in
the
fi
le

任何人都知道这是为什么吗?

c arrays char delimiter strtok
1个回答
0
投票

这是因为sizeof(word2)为4(word2是一个指针,所以它是4个字节长)。因此,您只需要从输入文件中索取4个字节。改为在len中使用fread,它应该会更好地工作。

© www.soinside.com 2019 - 2024. All rights reserved.