尝试使用 fgets 读取两行。为什么它只读第一行?

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

我正在尝试使用 fgets 读取两行,但只读取了第一行,然后 returns 出现了分段错误。我不确定我需要更改什么才能在第二行中读取它。如有任何帮助,我们将不胜感激!

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

您的代码中有两部分的函数调用顺序有误;您在调用 strtok() 之后又调用了 printf() 而未检查 NULL。修复如下:

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

关于:

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

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

函数:strtok() 可以 return NULL。

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

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

建议:

word = strtok(str," ");

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