- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- int a2i(const char *s)
- {
- int res = 0, len, tmp, op = 0;
- register int j, k;
- len = strlen(s);
- for(j=0; j < len; j++)
- {
- if(s[0] == '-' && j == 0)
- {
- op = 1;
- continue;
- }
- if('0' > s[j] || s[j] > '9')
- {
- printf("wrong parameter\\n");
- exit(1);
- }
- tmp = (s[j] - '0');
- for(k=1; k < (len -j); k++)
- tmp *= 10;
- tmp = op == 1 ? -tmp : tmp;
- res += tmp;
- if(op == 1) // 负数
- {
- if(res >=0 && len != 1) // excluding in[0] == 0
- {
- printf("\\"int\\" negative overflow...\\n");
- exit(1);
- }
- }else{
- if(res <= 0 && len != 1) // excluding in[0] == 0
- {
- printf("\\"int\\" positive overflow...\\n");
- exit(1);
- }
- }
- }
- return res;
- }
- int main(int argc, char *argv[])
- {
- if(argc != 2)
- {
- fprintf(stderr, "%s number\\n", argv[0]);
- exit(1);
- }
- printf("res = %d\\n", a2i(argv[1]));
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1704201512288.html
来源: http://www.codesnippet.cn/detail/1704201512288.html