vc++中itoa()这个函数不能实现应用什么替代
发布网友
发布时间:2023-07-22 06:08
我来回答
共2个回答
热心网友
时间:2023-09-13 13:05
要不你试试自己增加一个
/*============itoa=============*/
/*把num转换成字符串存放在str 指向的字符串里*/
int myitoa(int num, char *str)
{
int temp;
int sign = 0; //标记num的符号
char *p;
if (str == NULL) return -1;
p = str;
/*负数的话取绝对值并改变标记*/
if (num < 0)
{
num = 0 - num;
sign = 1;
}
/*把数从低位放进字符串*/
do
{
temp = num % 10; //取num的最后一位
*(p++) = temp + '0';
}while ((num /= 10) != 0);
/*是负数的时候添加‘-’*/
if (sign == 1)
{
*(p++) = '-';
}
/*给字符串的末尾添加 ''/0*/
*(p+1) = '/0';
/*字符串逆置*/
while(str < p)
{
*str = *str + *p;
*p = *str - *p;
*str = *str - *p;
str++;
p--;
}
return 0;
}
/*========atoi========*/
/*把str指向的字符串转换成数字*/
#include <stdlib.h>
int myatoi(const char *str)
{
int sum = 0;
int sign = 0;
if (str == NULL)
{
perror("The string is NULL!/n");
exit(-1);
}
/*判断是否为负数*/
if (*str == '-')
{
sign = 1;
str++;
}
/*转换*/
while (*str != '/0')
{
sum = 10*sum + (*str - '0');
str++;
}
/*判断是否为负数*/
if(sign == 1)
{
sum = 0 - sum;
}
return sum;
}
另外还写 float 与 字符串 转换,代码如下
/*
*File : ftoa.c
*/
/*Float ===> String*/
int ftoa(char *str, float num, int n) //n是转换的精度,即是字符串'.'后有几位小数
{
int sumI;
float sumF;
int sign = 0;
int temp;
int count = 0;
char *p;
char *pp;
if(str == NULL) return -1;
p = str;
/*Is less than 0*/
if(num < 0)
{
sign = 1;
num = 0 - num;
}
sumI = (int)num; //sumI is the part of int
sumF = num - sumI; //sumF is the part of float
/*Int ===> String*/
do
{
temp = sumI % 10;
*(str++) = temp + '0';
}while((sumI = sumI /10) != 0);
/*******End*******/
if(sign == 1)
{
*(str++) = '-';
}
pp = str;
pp--;
while(p < pp)
{
*p = *p + *pp;
*pp = *p - *pp;
*p = *p -*pp;
p++;
pp--;
}
*(str++) = '.'; //point
/*Float ===> String*/
do
{
temp = (int)(sumF*10);
*(str++) = temp + '0';
if((++count) == n)
break;
sumF = sumF*10 - temp;
}while(!(sumF > -0.000001 && sumF < 0.000001));
*str = '/0';
return 0;
}
/*
* File : atof.c
*/
/*String ===> Float*/
float atof(const char *str)
{
float sumF = 0;
int sumI = 0;
int sign = 0;
if(str == NULL) return -1;
/*Is less than 0 ?*/
if(*str == '-')
{
sign = 1;
str++;
}
/*The part of int*/
while(*str != '.')
{
sumI = 10*sumI + (*str - '0');
str++;
}
/*Let p point to the end*/
while(*str != '/0')
{
str++;
}
str--; //Your know!
/*The part of float*/
while(*str != '.')
{
sumF = 0.1*sumF + (*str - '0');
str--;
}
sumF = 0.1*sumF;
sumF += sumI;
if(sign == 1)
{
sumF = 0 - sumF;
}
return sumF;
}
转载一个大侠的代码
热心网友
时间:2023-09-13 13:06
sprintf( );
或者 CString str;
str.Format( );