atoi函数
来源:互联网 发布:黑名单软件 编辑:程序博客网 时间:2024/05/23 13:24
- 原型:int atoi (const char *nptr)
- 用法:#include <stdlib.h>
- 功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号才开始做转换,而再遇到非数字或字符串时('\0')才结束转化,并将结果返回。
- 说明:atoi()函数返回转换后的整型数。
- 举例:
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- char a[] = "-100";
- char b[] = "456";
- int c = 0;
- c = atoi(a) + atoi(b);
- printf("c = %d\n",c);
- }
结果:
- 举例2:
1
2
3
4
5
6
7
8
9
10
11
#include <stdlib.h>
#include <stdio.h>
int
main(
void
)
{
float
n;
char
const
*str =
"12345.67"
;
n =
atoi
(str);
printf
(
"string=%sint=%dfloat=%f\n"
,str,n,n);
return0;
}
输出:
string = 12345.67 int=12345float = 12345.000000
2)
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdlib.h>
#include <stdio.h>
int
main()
{
char
a[] =
"-100"
;
char
b[] =
"123"
;
int
c;
c =
atoi
(a) +
atoi
(b);
printf
(
"c=%d\n"
, c);
return
0;
}
执行结果:
c = 23
- 函数实现:
atoi()函数实现的代码:
- /*
- * 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 ()
- 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;
- }
0 0
- atoi函数
- atoi函数
- atoi () 函数
- atoi函数
- atoi()函数
- atoi 函数
- atoi函数
- atoi函数
- atoi函数
- atoi函数
- atoi函数
- atoi函数
- atoi函数
- atoi()函数
- atoi函数
- atoi函数
- atoi()函数
- atoi函数
- hdu 4027 线段树
- 一个简单的Spring4和MyBatis事务的例子(很详细)
- C語言及程序設計初步第11講-項目3:如何買玫瑰
- 常见的几种文件或访问路径详解
- 公开课机器学习笔记(1)回归分析
- atoi函数
- python分布式进程
- 关于spring”通配符的匹配很全面, 但无法找到元素 'context:component-scan' 的声明“的错误
- Python基础03 序列
- 【全入口时代】App、web、微信,一个都不能少
- maven package 命令打包
- 深入理解 C# 协变和逆变
- windows环境用git bash下载android源码
- 升级Xcode到6.1之后使用iPhone6真机测试cocos2d-x报错不支持arm64的解决方案,Undefin ...