Search code examples
cfgets

Trying to read in two lines using fgets. Why is it only reading the first line?


I am trying to read in two lines using fgets, but only the first line is read and then returns a segmentation fault. I'm not sure what I would need to change for it to read in the second line. Any help would be appreciated!

int main(void)
{
  char str[100];
  char *word;

  //First Line                                                                                        
  fgets(str, 100, stdin);
  printf("%s", str);

  word = strtok(str," ");
  printf("%s\n", word);

  while(word != NULL)
    {
      word = strtok(NULL," ");
      printf("%s\n", word);
  }

  //Second Line                                                                                       
  fgets(str, 100, stdin);
  printf("%s", str);

  word = strtok(str," ");
  printf("%s\n", word);

  while(word != NULL)
    {
      word = strtok(NULL," ");
      printf("%s\n", word);
    }

  return 0;
}

Solution

  • You got the order of function calls wrong in two parts of your code; Your are calling printf() after calling strtok() without checking for NULL. Fix it as follows:

    int main(void)
    {
        char str[100];
        char *word;
    
        //First Line                                                                                        
        fgets(str, 100, stdin);
        printf("Printing entire string: %s\n", str);
    
        word = strtok(str, " ");
        printf("Printing tokens:\n");
    
        while (word != NULL)
        {
            printf("%s\n", word);
            word = strtok(NULL, " ");
        }
    
        //Second Line                                                                                       
        fgets(str, 100, stdin);
        printf("Printing entire string: %s\n", str);
    
        word = strtok(str, " ");
        printf("Printing tokens:\n");
    
        while (word != NULL)
        {
            printf("%s\n", word);
            word = strtok(NULL, " ");
        }
        return 0;
    }