一道思考不出来的C语言题目,请教Tong..
我想表达意思是我字符串是可以以指针把里面内容取出来. 但是取出来之后也只能存到数组里. 怎么去转成INT ?题目:
请实现一个函数,将一个String 转成int 函数原型如下:
int atoi(char *s);
#include <stdio.h> int atoi(char *s) { int length=0,sum = 0; char *p = s; while(*p++) {length++;} //求出s的长度 p = s; while(length>1) { sum+= *p-'0'; //从首位起逐个加到sum中 sum*=10; length--; p++; } sum+= *p-'0'; //加上个位数的时候就不需要再sum*=10了。 return sum; } int main(int argc, char *argv[]) { char buff[20]; printf("input a string: "); scanf("%s",buff); printf("atoi(buff) is: %d",atoi(buff)); return 0; }
isspace(int x) { if(x==' '||x=='\t'||x=='\n'||x=='\f'||x=='\b'||x=='\r') return 1; else return 0; } isdigit(int x) { if(x<='9'&&x>='0') return 1;x` else return 0; } int atoi(const char *nptr) { int c; /* current char */ int total; /* current total */ int sign; /* if '-', then negative, otherwise positive */ /* skip whitespace */ while ( isspace((int)(unsigned char)*nptr) ) ++nptr; c = (int)(unsigned char)*nptr++; sign = c; /* save sign indication */ if (c == '-' || c == '+') c = (int)(unsigned char)*nptr++; /* skip sign */ total = 0; while (isdigit(c)) { total = 10 * total + (c - '0'); /* accumulate digit */ c = (int)(unsigned char)*nptr++; /* get next char */ } if (sign == '-') return -total; else return total; /* return result, negated if necessary */ }