如何把字符串类型转换成数字类型?

方法一:

#include<stdio.h>
int main()
{
   int i=0,num=0;
   char *a=”45678″;
   for(i=0;i<5;i++)
   {
      num=num*10+a[i]-‘0’;  //这里是完成一位数的转换,比如i=0,num=0*10+4=4,i=1,num=4*10+5=45,一直到后面,就全部转化了
   }
   printf(“%d\n”,num);
   return 0;

}

结果:

liuzj@ET302Buildver:~/zhanghong/king/20180224$ ./a.out 
45678

liuzj@ET302Buildver:~/zhanghong/king/20180224$ 

方法二:用aoti函数:

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
    int n;
    char *str = “12345”;
    n = atoi(str);
    printf(“int=%d\n”,n);
    return 0;

}

liuzj@ET302Buildver:~/zhanghong/king/20180224$ vim atoi.c
liuzj@ET302Buildver:~/zhanghong/king/20180224$ gcc atoi.c
liuzj@ET302Buildver:~/zhanghong/king/20180224$ ./a.out 
int=12345
liuzj@ET302Buildver:~/zhanghong/king/20180224$ 

    原文作者:Makefilehoon
    原文地址: https://blog.csdn.net/Makefilehoon/article/details/79368581
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞