0
votes

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"

2
You never initialize count. Turn on your compiler warnings and heed them. Also... er... Have you not learned about strcpy() yet?Shawn
@Shawn, thanks for the reply, I posted an updated codej.bucz
How to "store" STDIN... So you want to use your 2D array as storage for everything you read from stdin? 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 than MAXSIZE lines.David C. Rankin
Are you trying to count distinct words ? what about multiple words per line ?dash-o

2 Answers

0
votes

Perhaps the question code is close.

  #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  count = 0;

    while(fgets(line, MAXSIZE, stdin))
      {
      printf("%s", line);
      strcpy(line1[count], line);
      printf("%s\n", line1[count]);  // instead of: printf("%s\n", line1[count][i]);

      count++;
      }

    return(0);
    }
0
votes

Your strcpy works as it should, but the printf caused a warning already at compile time, change the printf-line from printf("%s\n", line1[count]); to printf("%s\n", line1[count]);

After the while loop you can verify your copy with:

for (int i=0; i < count; i++){
    printf("%d: %s",i, line[i]);
}

Although fgets will put a terminating 0-byte at the end of the buffer, it would be more defensive to user strncpy which is guaranteed not copy more than n-bytes, but in this example you could eliminate the copy altogether by writing directly in to line[count] buffer.

Also you shod take care and stop reading before overwriting your buffers. When you call fgets you limit the read to MAXSIZE which is good but you should also check count is below MAXWORDS