我试图写的代码应该从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 Filen");
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("%sn",word);
word = strtok(NULL," ");}
exit(0);
}
问题是,我得到的输出不仅是文本(现在作为单独的字符串),而且还有一些字符是r(这是回车),但也241r 02,我无法找出它们是什么?你能帮我吗?
主要的问题是您从来没有在您构建的字符串的末尾放置空终止符。
改变:
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] = ' ';
word=strtok(words," ");