Strtok问题C(EOF字符?)

时间:2011-12-30 22:37:19

标签: c string text eof strtok

我试图编写的代码应该从txt文件中读取文本并分成字符串。我来到以下代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
    FILE *fp;
    int i=0;
    char *words=NULL,*word=NULL,c;
    if ((fp=fopen("monologue.txt","r"))==NULL){ /*Where monologue txt is a normal file with plain text*/
        printf("Error Opening File\n");
        exit(1);}
    while ((c = fgetc(fp))!= EOF){
        if (c=='\n'){ c = ' '; }
        words = (char *)realloc(words, ++i*sizeof(char));
        words[i-1]=c;}
    word=strtok(words," ");
    while(word!= NULL){
        printf("%s\n",word);
        word = strtok(NULL," ");}
    exit(0);
}

问题是我得到的输出不仅是文本(现在作为单独的字符串)而且还有一些字符是\ r \ n(它是回车符)而且\ 241 \ r \ 002我无法找到它们是什么?你能救我一下吗?

1 个答案:

答案 0 :(得分:2)

主要问题是你永远不会在你建立的字符串的末尾放置一个空终结符。

变化:

    while ((c = fgetc(fp))!= EOF){
        if (c=='\n'){ c = ' '; }
        words = (char *)realloc(words, ++i*sizeof(char));
        words[i-1]=c;}
    word=strtok(words," ");

要:

    while ((c = fgetc(fp))!= EOF){
        if (c=='\n'){ c = ' '; }
        ++i;
        words = (char *)realloc(words, i + 1);
        words[i-1]=c;}
    words[i] = '\0';
    word=strtok(words," ");