标签:
//编写函数实现库函数atoi,把字符串转换成整形 #include <stdio.h> #include <string.h> #include <assert.h> #include <ctype.h> long long calculate(const char *src, int flag) { long long num = 0; while (*src ) { if ((*src >= '0') && (*src <= '9'))//判断输?入是否为?非数组字符 { num = num * 10 + (*src - '0'); if ((flag == 1 && num>0x7fffffff) || (flag == -1 && num < (signed int)0x80000000))//考虑数字太?大 { num = 0; break; } src++; } else { num = 0; break; } } return flag * num; } long long str_to_int(const char *str) { long long num = 0; if (str != NULL && *str != '\0') { while (isspace(*str)) { str++; } int flag = 1; if (*str == '+') str++; else if (*str == '-') { str++; flag = -1; } if (*str != '\0') { num = calculate(str, flag); } } return num; } int main() { printf("%lld\n", str_to_int(" +2345")); printf("%lld\n", str_to_int(" -2345")); printf("%lld\n", str_to_int("+2345")); printf("%lld\n", str_to_int("-2345")); printf("%lld\n", str_to_int("2345")); printf("%lld\n", str_to_int("-111111111")); printf("%lld\n", str_to_int("")); printf("%lld\n", str_to_int("123ab")); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
【C语言】编写函数实现库函数atoi,把字符串转换成整形(考虑数字过大)
标签:
原文地址:http://blog.csdn.net/doudouwa1234/article/details/46761867