一、库函数
1.1 atoi
字符串转换成int
型整数
1.1.1 函数原型
int atoi(const char* str);
- 参数为待转换的字符串地址;
- 函数返回转换的整数。
1.1.2 函数说明
- 函数返回 int 类型,因此对于超出 10 位的字符串,转换必会出错, 10位也可能出错,因为 int 的最大值为 2,147,483,647 。
- 函数转换流程为:从左到右,先跳过空白字符,找到空白字符后的数字字符,数字字符后的其他非数字字符将被忽略。若字符串中的第一个非空白字符不是有效整数,或str为空,或仅包含空白字符,函数返回0
1.1.3 使用举例
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char str1[11] = {
0}, str2[11] = {
0}, str3[11] = {
0}, str4[15] = {
0};
int num1, num2, num3, num4;
strcpy(str1, " 12snd34f.6");
strcpy(str2, " ab12,st");
strcpy(str3, "1111111111");
strcpy(str4, "11111111111");
num1 = atoi(str1);
num2 = atoi(str2);
num3 = atoi(str3);
printf("%d\n%d\n%d\n%d\n", num1, num2, num3, num4);
return 0;
}
输出结果:
(最后一位数据溢出)