I need to read in words from a text file and then count the occurrences of each word but I can't figure out how to store the words in a variable.
I read the code in using fgets, and then i can print it using printf. However when I try to store the character array in a different array that I can use to compare the character arrays later, i keep getting seg faults. How can I go about saving the character array "line" in a different array?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 500
#define MAXWORDS 1000
int main ( int argc, char *argv[] ) {
char line[MAXSIZE];
char line1[MAXWORDS][MAXSIZE];
int i,j,k;
int count = 0;
while ( fgets ( line, MAXSIZE, stdin ) != NULL ) {
printf("%s", line);
strcpy(line1[count], line);
printf("%s\n", line1[count][i]);
count++;
}
return(0);
}
(This is my updated code, it still prints the first line and then seg faults.)
when I compile and run this code, it prints the first line of the text file and then returns "segmentation fault"
count
. Turn on your compiler warnings and heed them. Also... er... Have you not learned aboutstrcpy()
yet? – Shawnstdin
? Fine, but horribly wasteful on storage for lines containing nothing but'\n'
or text like"okay"
. You also need to limit the number of lines you attempt to store to less thanMAXSIZE
lines. – David C. Rankin