zoukankan      html  css  js  c++  java
  • 整型与字符型之间转化

    整数转化为字符串                       


    1、可以使用itoa函数(注意,这个函数时在stdlib库中)

    char *itoa(int value, char *string, int radix);
          value: 被转换的整数
          string: 转换后储存的字符数组
          radix: 转换进制数,如2,8,10,16 进制等

    #include <stdio.h>
    #include <stdlib>
    
    int main()
    {
        int num = 12345;
        char str[7];
    
        itoa(num,str,10);
    
        printf("输出:%s",str);
        return 0;
    }


    2、自定义函数

            采用加‘0’,再逆序的方法,整数加‘0’就可以隐性的转化为char型(加减‘0’可以使得在int和char之间转化)

    char* IntToStr(int num,char* str)
    {
        if(NULL == str)
            return NULL;
    
        int i = 0,j = 0;//注意初始化
        char temp[100];
        while(num){
            temp[i] = num%10 + '0';//一个整数转化成字符型
            num = num /10;
            i++;
        }
        temp[i] = '';//字符串结束标志
    
        i = i - 1;//i返回到temp最后一个有意义的数字
        while(i >= 0){
            str[j] = temp[i];
            j++;
            i--;
            //str[j++] = temp[i--];
        }
        return str;
    }


    字符串转化为整数                      


    1、使用非标准C函数atoi

            int atoi(const char *nptr);参数nptr字符串,如果第一个非空格字符存在,是数字或者正负号则开始做类型转换,之后检测到非数字(包括结束符 ) 字符时停止转换,返回整型数。否则,返回零

    #include <sddio.h>
    #include <stdlib.h>
    
    int main()
    {
        char str[] = "12345";
        int num;
        
        num = atoi(str);
        printf("num = %d"num);
        return 0;
    }


    2、自定义函数

    int StrToInt(char*str)
    {
        if(NULL == str)
            return -1;
    	
        int res = 0;
        bool flag = false;
        if(str[0] == '-' || str[0] == '+'){
    	flag = (*str++ != '+');
        }
        while(*str){
    	res = res*10 + (*str++ -'0');
        }
        return flag ? -res : res;
    }


  • 相关阅读:
    DFC-3C和DFC-3B的区别和注意事项
    Bug搬运工-CSCux99539:Intermittent error message "Power supply 2 failed or shutdown"
    EVE上传Dynamips、IOL和QEMU镜像
    EVE扩大虚拟内存
    EVE磁盘扩容
    VMware安装EVE
    介绍Mobility Group
    Bug搬运工-CSCvi02106 :Cisco 2800, 3800, 1560 APs: when connected to a Cisco Switch CDP-4-DUPLEX_MISMATCH log is seen
    jquery.autocomplete在火狐下的BUG解决
    nodeJS中exports和mopdule.exports的区别
  • 原文地址:https://www.cnblogs.com/james1207/p/3318037.html
Copyright © 2011-2022 走看看