网站建设包括哪些服务,惠州最专业的网站建设公司,网页游戏传奇霸主攻略,phpcms v9网站导航目录 一、前言二、声明三、描述四、参数五、返回值六、使用七、模拟实现 一、前言 二、声明
int atoi(const char *str)三、描述
C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数#xff08;类型为 int 型#xff09;需要包含头文件#xff… 目录 一、前言二、声明三、描述四、参数五、返回值六、使用七、模拟实现 一、前言 二、声明
int atoi(const char *str)
三、描述
C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数类型为 int 型需要包含头文件stdlib.h
四、参数
str – 要转换为整数的字符串。
五、返回值
该函数返回转换后的长整数如果没有执行有效的转换则返回零。
六、使用
#include stdio.h
#include stdlib.h
#include string.hint main()
{int val;char str[20];strcpy(str, 98993489);val atoi(str);printf(字符串值 %s, 整型值 %d\n, str, val);strcpy(str, www.com);val atoi(str);printf(字符串值 %s, 整型值 %d\n, str, val);return(0);
} 七、模拟实现
思路 1.如果开始遇到了空格 那么需要一直过滤 2. - 会影响 这个数字 的正负 3. 在这个字符串当中 如果出现了非数字字符 那么就结束转换 4. 如果 转换之后的数字 大于 int 最大值 那么按照最大值算 如果小于最小值 按照最小值算
#include stdio.h
#include stdlib.h
#include string.h
#includectype.h
#includeassert.h
enum State//判断是否是合法转化
{VALLD,//合法INVALLD//非法
}stateINVALLD;
int my_atoi(const char* str)
{assert(*str!NULL);if(*str \0){//空字符串返回0return 0;}if (isspace(*str))//返回值不为0代表是空格{str;}//到这里str后面就一定不是空格了int flag 1;if (*str ){flag 1;str;}else if(*str -){flag -1;str;}//需要把字符串中所有的字符串全部判断一遍long long ret 0;while (*str ! \0){if (isdigit(*str)){//是数字字符 把字符1转换为数字1——》 ’1‘-’0‘1ret ret*10 (*str - 0) * flag;if (ret INT_MAX){ret INT_MAX;}if (ret INT_MIN){ret INT_MIN;}}else{// 不是数字字符return (int)ret;}str;}if (*str \0){state VALLD;}return (int)ret;
}
int main()
{int val;char str[20];strcpy(str, 98993489);val atoi(str);printf(字符串值 %s, 整型值 %d\n, str, val);strcpy(str, www.com);val atoi(str);printf(字符串值 %s, 整型值 %d\n, str, val);int nummy_atoi(123);if (state VALLD){printf(合法转化%d\n, num);}else{printf(不合法转化%d\n, num);}return 0;
}运行结果 欧耶我学会啦