【发布时间】: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