I have a text file with random words stored in an unstructured way. (Unstructured meaning random spaces and blank lines) - e.g. of the text file:
file.txt
word1 word2 word3
word4
word5
word6
I'm want to read each of these words into a char array. I tried the following:
FILE *fp
fp = fopen("file.txt","r")
int numWords =0;
char *arr = malloc(sizeof(char *));
while(!feof(fp)){
fscanf(fp, "%s", arr);
numWords++;
}
fclose(fp);
For some reason, I can't access each word from the array. i.e. I'm expecting printf("%s", arr[0])
to return word1
, etc. However, arr[0]
stores a character, in this case w
.
There is also another problem. I put a printf
statement in the while
loop and it prints the last word, word6
twice, meaning the loop is executed an extra time at the end for some reason.
If someone could help me on how to achieve this objective that would be much appreciated, thanks!