【发布时间】:2020-10-17 18:32:29
【问题描述】:
我想把每个单词都放在一个数组中。
这是代码。
这是输出
据我所知,每次我有一个新行时,数组的第一个单词都会被文件下一行的第一个单词替换,但我不明白为什么。 我在这里没有显示,但是在新行之后,所有其他位置都是错误的。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX_LINE_LEN 256
void usage (const char *prog) {
fprintf (stderr, "Usage (words): %s [file_path]\n", prog);
exit (1);
}
void split_print_words (const char *filename) {
FILE *fd = stdin; // By default will read from stdin
if (filename != NULL && strcmp (filename, "-") != 0) {
// A file name was given, let's open it to read from there
fd = fopen (filename, "r");
assert (fd != NULL);
}
char buffer[MAX_LINE_LEN];
while(fgets(buffer, sizeof(buffer), fd != NULL)) {
char *token;
token = strtok(buffer, " \n");
while(token!=NULL) {
write(1, token, strlen(token));
write(1, "\n", 1);
token = strtok(NULL, " \n");
}
}
}
int main (int argc, char *argv[]) {
// Check there is one and only one argument
if (argc < 1 || argc > 2) {
usage (argv[0]);
}
split_print_words (argv[1]);
exit (0);
}
【问题讨论】:
-
请将代码和输入/输出示例包含为文本,而不是模糊图像。
-
有输入输出和代码的照片,我看得很清楚
-
但是我们不想要照片,我们想要可以复制和粘贴的文本。见:minimal reproducible example
-
为什么你的 strtok 分隔符是“\t\n”?如果要将句子拆分为单词,则分隔符应该只是一个空格:“”。此外,看起来您每次都在打印 words[0],而不是 words[nwords]。
-
将
fd == NULL作为第三个参数传递给fgets是一个错误。这将 [可能] 评估为 0(即NULL)。您希望第三个参数 [简单地] 是:fd。你想要:while(fgets(buffer, sizeof(buffer), fd) != NULL) {