1

我在使用 atof 和 strtok 时遇到问题。

#include<stdio.h> // printf
#include<stdlib.h> // atof
#include<string.h> // strtok

int main()
{
  char buf[256]="123.0 223.2 2314.2";
  char* tp;

  printf("buf : %s\n", buf);
  tp = strtok(buf," ");
  printf("tp : %g ", atof(tp));
  while (tp!=NULL) {
    tp = strtok(NULL," ");
    printf("%g ", atof(tp));
  }

  return 0;
}

我可以编译上面的代码,它不会返回任何错误或警告消息。但是当我执行“a.out”时,它会返回如下所示的分段错误。

78746 Segmentation fault: 11  ./a.out

我不知道有什么问题。如我所见,上面的代码不会复合语法错误。

4

2 回答 2

11

tp变为null时,你atof就可以了!

像这样重写你的循环:

int main()
{
  char buf[256]="123.0 223.2 2314.2";
  char* tp;

  printf("buf : %s\n", buf);
  tp = strtok(buf," ");
  printf("tp :");
  while (tp!=NULL) {
    printf("%g ", atof(tp));
    tp = strtok(NULL," ");
  }

  return 0;
}
于 2013-12-03T12:49:13.510 回答
3

您将 tp 传递给 atof 而不检查它是否为非空。

于 2013-12-03T12:50:52.847 回答