2011-12-30 51 views
0

我试图编写的代码应该读取txt文件中的文本并将其分离为字符串。我是来下面的代码:Strtok问题C(EOF字符?)

#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(这是回车),但也\ 241 \ r \ 002,我无法找出他们是什么?你能帮我吗?

+0

是您的文件保存为Unicode? – Ulterior 2011-12-30 22:39:03

+0

您可以为每个输入字符调用'realloc(),将缓冲区的大小增加1个字节。这可能是非常低效的。按需要加倍缓冲区大小会更快。你需要检查'realloc()'是成功还是失败。 – 2011-12-30 23:05:31

回答

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," "); 
+0

我该如何避免? – Melkon 2011-12-30 22:41:32

+0

现在完美的工作,但我不明白我的代码为什么 word = strtok(NULL,“”);需要 才能正确打印单词,而且如果我只想使用单词指针,如何访问单词指针中的每个单词? – Melkon 2011-12-30 23:00:27

+1

@Konstantinos:需要'strtok(NULL,“”)'来获得下一个标记 - 这就是'strtok()'设计的工作方式。我不确定你评论中的第二个问题是什么意思。 – 2011-12-31 00:23:46