atoi() 函数与 itoa() 函数:字符串与数值之间的转换

来源:互联网 发布:go并发编程实战 2017 编辑:程序博客网 时间:2024/05/22 08:11

     在 C 语言中, atoi() 函数是实现字符串转换成数字,atoi() 函数源码:

isspace(int x){ if(x==' '||x=='\t'||x=='\n'||x=='\f'||x=='\b'||x=='\r')  return 1; else    return 0;}isdigit(int x){ if(x<='9'&&x>='0')           return 1;x`  else   return 0;}int atoi(const char *nptr){        int c;              /* current char */        int total;         /* current total */        int sign;           /* if '-', then negative, otherwise positive */        /* skip whitespace */        while ( isspace((int)(unsigned char)*nptr) )            ++nptr;        c = (int)(unsigned char)*nptr++;        sign = c;           /* save sign indication */        if (c == '-' || c == '+')            c = (int)(unsigned char)*nptr++;    /* skip sign */        total = 0;        while (isdigit(c)) {            total = 10 * total + (c - '0');     /* accumulate digit */            c = (int)(unsigned char)*nptr++;    /* get next char */        }        if (sign == '-')            return -total;        else            return total;   /* return result, negated if necessary */}


      itoa() 函数是实现数字转换成字符串,源码如下:

void my_itoa(int n,char s[])    {        int i,j,sign;            if((sign=n)<0)    //记录符号            n=-n;         //使n成为正数        i=0;        do{            s[i++]=n%10+'0';    //取下一个数字        }while((n/=10)>0);      //循环相除            if(sign<0)            s[i++]='-';        s[i]='\0';        for(j=i-1;j>=0;j--)        //生成的数字是逆序的,所以要逆序输出            printf("%c",s[j]);    }


原创粉丝点击