#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我无法找到它们是什么?你能救我一下吗?
答案 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," ");