C库函数——字符串转数字整理

时间:2022-10-01 21:02:49

atof(将字符串转换成浮点型数)
atoi(将字符串转换成整型数)
atol(将字符串转换成长整型数)
strtod(将字符串转换成浮点数)
strtol(将字符串转换成长整型数)
strtoul(将字符串转换成无符号长整型数)
toascii(将整型数转换成合法的ASCII 码字符)
toupper(将小写字母转换成大写字母)
tolower(将大写字母转换成小写字母)

C库函数——字符串转数字整理C库函数——字符串转数字整理
 1 int atoi(const char *nptr)
 2 {
 3         int c;              /* current char */
 4         int total;         /* current total */
 5         int sign;           /* if '-', then negative, otherwise positive */
 6 
 7         /* skip whitespace */
 8         while ( isspace((int)(unsigned char)*nptr) )
 9             ++nptr;
10 
11         c = (int)(unsigned char)*nptr++;
12         sign = c;           /* save sign indication */
13         if (c == '-' || c == '+')
14             c = (int)(unsigned char)*nptr++;    /* skip sign */
15 
16         total = 0;
17 
18         while (isdigit(c)) {
19             total = 10 * total + (c - '0');     /* accumulate digit */
20             c = (int)(unsigned char)*nptr++;    /* get next char */
21         }
22 
23         if (sign == '-')
24             return -total;
25         else
26             return total;   /* return result, negated if necessary */
27 }
atoi函数源码
C库函数——字符串转数字整理C库函数——字符串转数字整理
 1 double atof(char s[])   //将字符串s转换成double型的浮点数  
 2 {  
 3   
 4     int i;  
 5     int sign;  
 6     int flag;  
 7     int expn;  
 8     double val;  
 9     double power;  
10   
11     sign = 1;  
12     flag = 0;  
13     power = 1.0;  
14     expn = 0;  
15     for(i = 0; isspace(s[i]); ++i)  
16         ;  
17     if(s[i] == '-')  
18         sign = -1;  
19     if(s[i] == '+' || s[i] == '-')  
20         ++i;  
21     for(val = 0.0; isdigit(s[i]); ++i)  
22         val = val * 10.0 + (s[i] - '0');  
23     if(s[i] == '.')  
24         ++i;  
25     for(; isdigit(s[i]); ++i)  
26     {  
27         val = val * 10.0 + (s[i] - '0');  
28         //power = power * 10.0;  
29         ++flag;  
30     }  
31     if(s[i] == 'e' || s[i] == 'E')  //如果写成s[i++] == 'e' || s[i++] == 'E',if(s[i] == '-')  
32                                     //则当输入的字符串带有E时,不能正确得到结果,这是因为在一  
33                                     //个语句中使用两次自增操作,引起歧义  
34         if(s[++i] == '-')  
35         {  
36             ++i;  
37             for(; isdigit(s[i]); ++i)  
38                 expn = expn * 10 + (s[i] - '0');  
39             expn = expn + flag;  
40             power = pow(10, expn);  
41             return sign * val / power;  
42         }  
43         else   
44         {  
45             for(; isdigit(s[i]); ++i)  
46                 expn = expn * 10 + (s[i] - '0');  
47             expn = expn - flag;  
48             power = pow(10, expn);  
49             return sign * val * power;  
50         }  
51   
52     power = pow(10, flag);  
53     return sign * val / power;  
54   
55 }  
atof函数代码