atoi函数

来源:互联网 发布:黑名单软件 编辑:程序博客网 时间:2024/05/23 13:24

  1.     原型:int  atoi (const  char  *nptr)
  2.     用法:#include  <stdlib.h>
  3.     功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回。
  4.     说明:atoi()函数返回转换后的整型数。
  5.     举例:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3.   
  4. int main()  
  5. {  
  6.     char a[] = "-100";  
  7.     char b[] = "456";  
  8.     int c = 0;  
  9.       
  10.     c = atoi(a) + atoi(b);  
  11.       
  12.     printf("c = %d\n",c);  
  13. }  

    结果:

  • 举例2:

1
2
3
4
5
6
7
8
9
10
11
#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
    float n;
    char const *str = "12345.67";
    n = atoi(str);
    printf("string=%sint=%dfloat=%f\n",str,n,n);
    return0;
}
输出:
string = 12345.67 int=12345float = 12345.000000
2)
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>
#include <stdio.h>
 
int main()
{
    char a[] = "-100";
    char b[] = "123";
    int c;
    c = atoi(a) + atoi(b);
    printf("c=%d\n", c);
    return 0;
}
执行结果:
c = 23
  • 函数实现:

atoi()函数实现的代码:

  1. /* 
  2. * name:xif 
  3. * coder:xifan@2010@yahoo.cn 
  4. * time:08.20.2012 
  5. * file_name:my_atoi.c 
  6. * function:int my_atoi(char* pstr) 
  7. */  
  8.   
  9. int my_atoi(char* pstr)  
  10. {  
  11.     int Ret_Integer = 0;  
  12.     int Integer_sign = 1;  
  13.       
  14.     /* 
  15.     * 判断指针是否为空 
  16.     */  
  17.     if(pstr == NULL)  
  18.     {  
  19.         printf("Pointer is NULL\n");  
  20.         return 0;  
  21.     }  
  22.       
  23.     /* 
  24.     * 跳过前面的空格字符 
  25.     */  
  26.     while(isspace(*pstr) == 0)  
  27.     {  
  28.         pstr++;  
  29.     }  
  30.       
  31.     /* 
  32.     * 判断正负号 
  33.     * 如果是正号,指针指向下一个字符 
  34.     * 如果是符号,把符号标记为Integer_sign置-1,然后再把指针指向下一个字符 
  35.     */  
  36.     if(*pstr == '-')  
  37.     {  
  38.         Integer_sign = -1;  
  39.     }  
  40.     if(*pstr == '-' || *pstr == '+')  
  41.     {  
  42.         pstr++;  
  43.     }  
  44.       
  45.     /* 
  46.     * 把数字字符串逐个转换成整数,并把最后转换好的整数赋给Ret_Integer 
  47.     */  
  48.     while(*pstr >= '0' && *pstr <= '9')  
  49.     {  
  50.         Ret_Integer = Ret_Integer * 10 + *pstr - '0';  
  51.         pstr++;  
  52.     }  
  53.     Ret_Integer = Integer_sign * Ret_Integer;  
  54.       
  55.     return Ret_Integer;  
  56. }  

    现在贴出运行my_atoi()的结果,定义的主函数为:int  main  ()

  1. int main()  
  2. {  
  3.     char a[] = "-100";  
  4.     char b[] = "456";  
  5.     int c = 0;  
  6.       
  7.     int my_atoi(char*);   
  8.   
  9.     c = atoi(a) + atoi(b);  
  10.       
  11.     printf("atoi(a)=%d\n",atoi(a));  
  12.     printf("atoi(b)=%d\n",atoi(b));  
  13.     printf("c = %d\n",c);  
  14.   
  15.     return 0;  
  16. }  


0 0
原创粉丝点击