龙空技术网

手写标准库函数atoi

coder人生 217

前言:

现在姐妹们对“c函数atoi”大体比较讲究,姐妹们都需要剖析一些“c函数atoi”的相关知识。那么小编也在网络上汇集了一些关于“c函数atoi””的相关资讯,希望各位老铁们能喜欢,兄弟们一起来学习一下吧!

1.如果传入的参数非法,比如并非是一个数字型字符串,函数该返回多少来表示参数异常呢?返回 -1 吗?但是如果待转换的字符串是 “-1”,那岂不是冲突了?

2.如果待转换的是负数,如果将最后的正数转换为负数呢?

3.考虑的不够全面,因为 atoi 对入参要完全符合条件。事实上 atoi 比我想象中的容错性更高。在找到第一个非空白字符之前,该函数首先根据需要丢弃尽可能多的空白字符(如 space 和 tab)。然后,从这个字符开始,取一个可选的正负号,后面跟着尽可能多的基数为 10 的数字,并将它们解释为一个数值。字符串可以在构成整数的字符之后包含其他字符,这些字符被忽略,对此函数的行为没有任何影响;

4.如果优雅地将数字字符转换为对应的数值,比如将字符 ‘0’ 转为数值 0;

5.如果转换的数值溢出了该返回什么呢?

#include <stdio.h>#include <ctype.h>#include <limits.h>// @brief: atoi converts a decimal value string to the corresponding valueint myatoi(const char* s){	// check null pointer	if (s == NULL) return 0;	int i,sign;	unsigned int n;	// skip white space	for (i = 0; isspace(s[i]); i++);	// get sign and skip	sign = (s[i]=='-')?-1:1;	if(s[i]=='+' || s[i]=='-') i++;	// convert numeric characters to numeric value	for(n=0; isdigit(s[i]); i++){       n = 10 * n + (s[i] - '0');	}		// overflow judgment	if (sign == 1 && n > INT_MAX) return INT_MAX;	if (sign == -1 && n > INT_MAX) return INT_MIN;	return sign * n;}int main(){	// normal positive int value with white-space character in front	const char* s0 = "\t1";	printf("1=%d\n", myatoi(s0));	// normal negtive int value with white-space character in front	const char* s1 = "\t-1";	printf("-1=%d\n", myatoi(s1));	// null pointer	const char* s3 = NULL;	printf("NULL=%d\n", myatoi(s3));	// invalid decimal value string	const char* s4 = "a123b";	printf("a123b=%d\n", myatoi(s4));	// out of max range	const char* s5 = "2147483648";	printf("2147483648=%d\n", myatoi(s5));	// out of min range	const char* s6 = "-2147483649";	printf("-2147483649=%d\n", myatoi(s6));}

标签: #c函数atoi