C将输入文本文件解析为单词

我试图解析输入文件(包含具有多行和分隔符的文本文档,即“!,。?”)为单词。 我的function’分裂function’是:

int splitInput(fp) { int i= 0; char line[255]; char *array[5000]; int x; while (fgets(line, sizeof(line), fp) != NULL) { array[i] = strtok(line, ",.!? \n"); printf("Check print - word %i:%s:\n",i, array[i]); i++; } return 0; } 

这是更正的function[抱歉额外的样式清理]:

 int splitInput(fp) { int i = 0; char *cp; char *bp; char line[255]; char *array[5000]; int x; while (fgets(line, sizeof(line), fp) != NULL) { bp = line; while (1) { cp = strtok(bp, ",.!? \n"); bp = NULL; if (cp == NULL) break; array[i++] = cp; printf("Check print - word %i:%s:\n",i-1, cp); } } return 0; } 

现在,看一下strtok的手册页,了解bp技巧

如果我正确理解您的问题,您想要读取每一行并将每行分成单词并将其添加到数组中。

  array[i] = strtok(line, ",.!? \n"); 

这不会有明显的原因,因为它只返回每一行的第一个单词而你永远不会分配内存。

这可能是你想要的。

  char *pch; pch = strtok(line, ",.!? \n"); while(pch != NULL) { array[i++] = strdup(pch); // put the content of pch into array at position i and increment i afterwards. pch = strtok(NULL, ",.!? \n"); // look for remaining words at the same line } 

尽管使用free ,但不要忘记释放你的数组元素。