0
votes

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;
}
2

2 Answers

3
votes

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;
}
0
votes

regarding:

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

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

the function: strtok() can return NULL.

The result is the call to printf() will be trying to print a value from address 0.

That is what is causing the seg fault.

Suggest:

word = strtok(str," ");

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