我有使用atof和strtok的问题.
#include// printf #include // atof #include // 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
我不知道是什么问题.正如我所见,上面的代码不会复合语法错误.
当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; }