最近补题时学了一种把字符串类型转换成数字型的方法,记录一下。
atoi (表示 ascii to integer):是把字符串转换成整型数的一个函数.。
说明:
1.int atoi(const char *nptr) 函数会扫描参数 nptr字符串,会跳过前面的空白字符(例如空格,tab缩进)等。
2.如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回 0 [1]。
3.特别注意,该函数要求被转换的字符串是按十进制数理解的。atoi输入的字符串对应数字存在大小限制(与int类型大小有关),若其过大可能报错-1。
同理可得:
atof():ascii to float,将字符串转换成双精度浮点型值;
atol():ascii to long,将字符串转换成长整型;
strtod():string to double,将字符串转换成双精度浮点型值,并报告不能被转换的所有剩余数字;
strtol():string to long,将字符串转换成长整型值,并报告不能转换的所有剩余数字;
代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
char ch[]="-123456";
cout<<atoi(ch)<<endl;
return 0;
}
-123456