【问题标题】:Why can't I properly extract tokens using delimiters in this code?为什么我不能在此代码中使用分隔符正确提取标记?
【发布时间】:2020-01-29 01:49:31
【问题描述】:

我正在编写代码以从 .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

有人知道这是为什么吗?

【问题讨论】:

  • 当您不明白为什么会得到结果时,最基本(但很有价值)的调试技术之一是打印计算机读取的数据,以便您知道它得到了什么,而不是什么你认为它得到了。例如,在循环的顶部,添加printf("Line: [[%s]]\n", word2);(确保在输出中包含换行符,以便及时显示。如果你这样做了,你要么立即解决了你的问题,要么你会一直在问一个不同的问题。

标签: c arrays char delimiter strtok


【解决方案1】:

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

【讨论】:

  • 啊,不知道我是怎么错过的。我认为我的 strtok 使用有问题。谢谢,非常感谢。
  • 我认为 OP 是 64 位机器,因为它需要拆分 7 个字符的段。
猜你喜欢
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
相关资源
最近更新 更多