1.先上atoi函数的功能概述:
将一个数字型字符串转换为int类型,注意数字的长度有限制,不要超过了int的范围。
atoi( ) 函数会扫描字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过isspace( )函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时(’\0’)才结束转换,并将结果返回。如果不能转换成 int 或者 nptr为空字符串,那么将返回 0。
2.实现代码:
#include <iostream>
#include<stdlib.h>
using namespace std;
int main()
{
cout<<"第一次输出"<<endl;
char s1[]="20000102";
int ints1=atoi(s1);
cout<<ints1<<endl;
ints1++;
cout<<ints1<<endl;
//2.遇到不属于数字的字符就停止读取,遇到空格则不影响
cout<<"第二次输出"<<endl;
char s2[]=" 200..00102";
int ints2=atoi(s2);
cout<<ints2<<endl;
ints2++;
cout<<ints2<<endl;
system("pause");
return 0;
}
结果:

3.不加 #include<stdlib.h>的报错图
解决办法:
加一个 #include<stdlib.h> 来解决
本文介绍了atoi函数的基本功能,即把字符串转换为整数的过程,并通过示例代码展示了如何使用该函数,包括处理非数字字符和空白字符的方法。

被折叠的 条评论
为什么被折叠?



