您的位置:首页 > 其它

C code 字符串与整数的相互转化

2016-06-21 10:09 309 查看
#include<stdio.h>
int str_to_int(const char *str,int *num);
void int_to_str(char str[],const int strLen,const int num);

int main(int argc,char *argv[])
{
char str[16];
int ret = 0,n = 0;
while(1)
{
scanf("%s",str);
ret = str_to_int(str,&n);
if(ret == 0)
{
printf("%d\n",n);
int_to_str(str,16,n);
printf("%s\n",str);
}
else
{
printf("error\n");
}
}
return 0;
}

int str_to_int(const char *str,int *num)
{
int sign = 1;
*num = 0;
const char *p = str;
while(*p != '\0')
{
if( *p >= '0' && *p <= '9' )
{
*num = *num * 10 + *p - '0';
p++;
}
else if( *p == '-' && *num == 0)
{
sign = -1;
p++;
}
else
{
return -1;
}
}
*num *= sign;
return 0;
}

void int_to_str(char str[],const int strLen,const int num)
{
int tmp = 0,n = 0,i = 0;
if(num < 0)
{
n = -num;
i = 1;
}
while(n != 0)
{
tmp = tmp * 10 + n%10;
n /= 10;
}
while(i<strLen && tmp != 0)
{
str[i++] = tmp % 10 + '0';
tmp /= 10;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: