atoi()函数的实现
2016-11-03 00:00
232 查看
atoi()函数的功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回(返回转换后的整型数)。
atoi()函数实现的代码:
[cpp]
view plain
copy
print?
/*
* name:xif
* coder:xifan@2010 @yahoo.cn
* time:08.20.2012
* file_name:my_atoi.c
* function:int my_atoi(char* pstr)
*/
int my_atoi(char* pstr)
{
int Ret_Integer = 0;
int Integer_sign = 1;
/*
* 判断指针是否为空
*/
if(pstr == NULL)
{
printf("Pointer is NULL\n");
return 0;
}
/*
* 跳过前面的空格字符
*/
while(isspace(*pstr) == 0)
{
pstr++;
}
/*
* 判断正负号
* 如果是正号,指针指向下一个字符
* 如果是符号,把符号标记为Integer_sign置-1,然后再把指针指向下一个字符
*/
if(*pstr == '-')
{
Integer_sign = -1;
}
if(*pstr == '-' || *pstr == '+')
{
pstr++;
}
/*
* 把数字字符串逐个转换成整数,并把最后转换好的整数赋给Ret_Integer
*/
while(*pstr >= '0' && *pstr <= '9')
{
Ret_Integer = Ret_Integer * 10 + *pstr - '0';
pstr++;
}
Ret_Integer = Integer_sign * Ret_Integer;
return Ret_Integer;
}
现在贴出运行my_atoi()的结果,定义的主函数为:int main ()
[cpp]
view plain
copy
print?
int main()
{
char a[] = "-100";
char b[] = "456";
int c = 0;
int my_atoi(char*);
c = atoi(a) + atoi(b);
printf("atoi(a)=%d\n",atoi(a));
printf("atoi(b)=%d\n",atoi(b));
printf("c = %d\n",c);
return 0;
}
atoi()函数实现的代码:
[cpp]
view plain
copy
print?
/*
* name:xif
* coder:xifan@2010 @yahoo.cn
* time:08.20.2012
* file_name:my_atoi.c
* function:int my_atoi(char* pstr)
*/
int my_atoi(char* pstr)
{
int Ret_Integer = 0;
int Integer_sign = 1;
/*
* 判断指针是否为空
*/
if(pstr == NULL)
{
printf("Pointer is NULL\n");
return 0;
}
/*
* 跳过前面的空格字符
*/
while(isspace(*pstr) == 0)
{
pstr++;
}
/*
* 判断正负号
* 如果是正号,指针指向下一个字符
* 如果是符号,把符号标记为Integer_sign置-1,然后再把指针指向下一个字符
*/
if(*pstr == '-')
{
Integer_sign = -1;
}
if(*pstr == '-' || *pstr == '+')
{
pstr++;
}
/*
* 把数字字符串逐个转换成整数,并把最后转换好的整数赋给Ret_Integer
*/
while(*pstr >= '0' && *pstr <= '9')
{
Ret_Integer = Ret_Integer * 10 + *pstr - '0';
pstr++;
}
Ret_Integer = Integer_sign * Ret_Integer;
return Ret_Integer;
}
现在贴出运行my_atoi()的结果,定义的主函数为:int main ()
[cpp]
view plain
copy
print?
int main()
{
char a[] = "-100";
char b[] = "456";
int c = 0;
int my_atoi(char*);
c = atoi(a) + atoi(b);
printf("atoi(a)=%d\n",atoi(a));
printf("atoi(b)=%d\n",atoi(b));
printf("c = %d\n",c);
return 0;
}
相关文章推荐
- 一个atoi的实现函数
- atoi() & itoa()函数的内部的实现
- atoi()函数的实现
- C语言笔试题(15)——atoi函数实现
- atoi()函数的实现
- atoi函数不同平台的实现问题
- atoi()函数的实现
- 基础函数的实现(strcpy,strcat, strcmp, atoi, itoa)
- 基础函数的实现(strcpy,strcat, strcmp, atoi, itoa)
- //实现一个atoi的函数,atoi是将字符串转换成整数
- 函数 atoi() 和 itoa() 的 C 语言实现。
- C语言实现strlen,atoi, strcpy等函数
- 学习笔记——atoi函数的用法及用C语言实现atoi
- 基础函数的实现(strcpy,strcat, strcmp, atoi, itoa)【转】
- atol(atoi)函数的实现要点
- atoi() & itoa()函数的内部的实现
- atoi的方法实现函数
- 学习笔记——atoi函数的用法及用C语言实现atoi
- 自己实现atoi函数功能,另加一个str2num有用的小程序
- atol(atoi)函数的实现要点