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

时间:2018-03-25 19:42:51

标签: c fgets

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 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

关于:

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

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

函数:strtok()可以返回NULL。

结果是对printf()的调用将尝试从地址0打印一个值。

这就是导致seg错误的原因。

推荐:

word = strtok(str," ");

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