首页 > 其他 > 详细

字符串和int转换函数实现

时间:2015-04-19 16:08:04      阅读:284      评论:0      收藏:0      [点我收藏+]
//不使用库函数将整数转换为字符串,输入 int 输出 char*

#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ char* IntoString(int num); //转换函数 int main(int argc, char** argv) { char *p1 = IntoString(-123); char *p2 = IntoString(13345666); while(*p1!=\0) std::cout<<*(p1++); std::cout<<std::endl; while(*p2!=\0) std::cout<<*(p2++); std::cout<<std::endl; delete p1; delete p2; return 0; } char* IntoString(int num) { int length = 0; if(num == 0) { return NULL ; } int temp_num = (num > 0 ? num: -num); while(temp_num!=0) //求正数的长度 { ++length; temp_num/=10; } int Yu = 0; if(num>0) //处理正整数 { char *pstr = new char[length + 1]; pstr[length] = \0; int Op_num = num; int n = length-1; while(Op_num !=0) { Yu = Op_num % 10; pstr[n--] = Yu+0; Op_num /= 10; } return pstr; } else { char *pstr = new char[length + 2]; //处理负整数 pstr[length+1] = \0; int Op_num = -num; int n = length; while(Op_num !=0) { Yu = Op_num % 10; pstr[n--] = Yu+0; Op_num /= 10; } pstr[0] = -; return pstr; } }

 

//不使用库函数将字符串转换为整数
//karllen   

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int StringToInt(const char *pstr);
int main(int argc, char** argv)
{
    char one[] = "1234";
    char two[] = "-14343";
    std::cout<<StringToInt(one)<<std::endl;
    std::cout<<StringToInt(two)<<std::endl;
    return 0;
}

int StringToInt(const char *pstr)
{
    int tempint = 0;
    const char *pt = pstr;
    if(*pt == + || *pt ==-)
    {
        ++pt;
    }
    while(*pt!=\0)
    {
        tempint = tempint*10 + (*pt - 0);
        ++pt; 
    }
    if(*pstr == -)
    {
        tempint = -tempint;
    }
    
    return tempint;
    
}

 

字符串和int转换函数实现

原文:http://www.cnblogs.com/Forever-Kenlen-Ja/p/4419975.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!