the code that i am trying to write is supposed to read text from a txt file and separate into strings. I have come to the following code:
#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);
}
The problem is that the output that i get is not only the text (now as separate strings) but also some characters that are \r(which is carriage return) but also \241\r\002 that i cant find out what they are? Can you help me out?
The main problem is that you never place a null terminator at the end of the string you build up.
Change:
To: