Chinaunix首页 | 论坛 | 博客
  • 博客访问: 271053
  • 博文数量: 40
  • 博客积分: 589
  • 博客等级: 中士
  • 技术积分: 549
  • 用 户 组: 普通用户
  • 注册时间: 2012-10-10 16:03
文章分类

全部博文(40)

文章存档

2013年(6)

2012年(34)

我的朋友

分类: C/C++

2012-12-20 14:37:39

/*
* FILE: lib/crtdll/stdlib/itoa.c
* PURPOSE: converts a integer to ascii
* PROGRAMER:
* UPDATE HISTORY:
* 1995: Created
* 1998: Added ltoa Boudewijn Dekker
*/

itoa函数原型
#include
#include
#include
/*整形转字符型*/
char *itoa(int value, char *string, int radix)
{
char tmp[33];
char *tp = tmp;
int i;
unsigned v;
int sign;
char *sp;

if (radix > 36 || radix <= 1)
{
__set_errno(EDOM);
return 0;
}

sign = (radix == 10 && value < 0);
if (sign)
v = -value;
else
v = (unsigned)value;
while (v || tp == tmp)
{
i = v % radix;
v = v / radix;
if (i < 10)
*tp++ = i+'0';
else
*tp++ = i + 'a' - 10;
}

if (string == 0)
string = (char *)malloc((tp-tmp)+sign+1);
sp = string;

if (sign)
*sp++ = '-';
while (tp > tmp)
*sp++ = *--tp;
*sp = 0;
return string;
}

/*长整形转字符型*/
char *ltoa(long value, char *string, int radix)
{
char tmp[33];
char *tp = tmp;
long i;
unsigned long v;
int sign;
char *sp;

if (radix > 36 || radix <= 1)
{
__set_errno(EDOM);
return 0;
}

sign = (radix == 10 && value < 0);
if (sign)
v = -value;
else
v = (unsigned long)value;
while (v || tp == tmp)
{
i = v % radix;
v = v / radix;
if (i < 10)
*tp++ = i+'0';
else
*tp++ = i + 'a' - 10;
}

if (string == 0)
string = (char *)malloc((tp-tmp)+sign+1);
sp = string;

if (sign)
*sp++ = '-';
while (tp > tmp)
*sp++ = *--tp;
*sp = 0;
return string;
}
/*无符号长整形转字符型*/
char *_ultoa(unsigned long value, char *string, int radix)
{
char tmp[33];
char *tp = tmp;
long i;
unsigned long v = value;
char *sp;

if (radix > 36 || radix <= 1)
{
__set_errno(EDOM);
return 0;
}


while (v || tp == tmp)
{
i = v % radix;
v = v / radix;
if (i < 10)
*tp++ = i+'0';
else
*tp++ = i + 'a' - 10;
}
if (string == 0)
string = (char *)malloc((tp-tmp)+1);
sp = string;

while (tp > tmp)
*sp++ = *--tp;
*sp = 0;
return string;
}

/*字符串转整形*/

#include "iostream.h"
int toi(const char * s)
{
int n = 0;

while(!(*s >= '0' && *s <= '9'))
s++;

while(*s >= '0' && *s <= '9')
{
n *= 10;
n += *s - '0';
s++;
}
return n;
}

阅读(6283) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

JozeTan2012-12-28 11:31:20

peibaoyi2012-12-23 14:16:13

toi函数太过简单,如果不考虑数的范围越界,不考虑负数,仅仅是将字符串转化为十进制数,程序应为:
int toi(const char* s)
{
    int n = 0;
    while((*s != 0) && !(*s >= '0' && *s <='9'))
       s++;
    if(*s == 0)
       return 0;
    while( (*s!=0) && (*s >='0' && *s <='9'))
    {
       n *= 10;