c/c++ 中的重要函数

1,strtod:

函数原型:

1 #include <cstdlib>
2 double strtod(const char *nptr, char **endptr);
strtod 原型

名称含义:

  strtod(将字符串转换成浮点数)

相关函数:

  strtof(float),strtol(long int),strtold(long double),strtoul(unsigned long int),strtoll(long long int),strtoull(unsigned long long int)

函数说明:

  strtod()会扫描参数 nptr 字符串,跳过前面的空格字符,直到遇上数字或者正负号才开始做转换,到出现非数字或字符串结束时('\0')时才结束转换,并将结果返回。

  若 endptr 不为 NULL,则会将遇到不合条件而终止的 nptr 中的字符指针由 endptr 传回,参数 nptr 字符串可能包含正负号、小数点或 E(e) 来表示指数部分。如123.456 或 123E-2。

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 
 4 int main() {
 5     char *endptr;
 6     char a[] = "1234.567qwer";
 7     printf("a=%lf\n", strtod(a, &endptr));  // a=1234.567000
 8     printf("endptr=%s\n", endptr);  // endptr=qwer
 9     return 0;
10 }
strtod 使用用例

2,atof:

函数原型:

1 #include<stdlib.h>
2 double atof(const char *ptr);
atof 原型

 名称含义:

  atof(把字符串转换为浮点数)。

相关函数:

  atoi(int),atol(long int),atoll(long long int)

函数说明:

  atof() 会扫描 nptr 字符串,跳过前面的空格,直到遇上数字或正负符号才开始做转换,而在遇到非数字或者字符串结束时('\0')才结束转换,并将结果返回。参数 nptr 字符串可能包含正负号、小数点或 E(e) 来表示指数部分。

附加说明:

  atof() 与 strtod(nptr,(char**)NULL) 结果相同,只是不能返回无效的字符串指针,如果不能转换,返回 0。

 

1 #include<stdlib.h>
2 int main() {
3     char* a = "-100.23";
4     char* b = "200E-2";
5     double c;
6     c = atof(a) + atof(b);
7     printf("c=%.2lf\n", c);  // c=-98.23
8     return 0;
9 }
atof 使用用例

 

 

  

 

posted on 2019-03-01 15:24  爱笑的张飞  阅读(306)  评论(0编辑  收藏  举报

导航