getline(): read a line from user input.
C语言: getline
01 int getline(char *str, int lim)
02 {
03 char c;
04 char *p=str;
05 while(--lim>0 && (c=getchar())!=EOF && c!='\n')
06 {
07 *p++=c;
08 }
09 *p='\0';
10 return p-str;
11 }
C语言: atoi
01 int atoi(char *p)
02 {
03 int n=0, sign;
04 //skip spaces
05 while(*p==' ')
06 p++;
07 //find the sign
08 sign=(*p=='-')?-1:1;
09 //skip the sign
10 if(*p=='-'||*p=='+')
11 p++;
12 //calculate the value
13 while((*p-'0')>=0&&(*p-'0')<=9)
14 {
15 n=10*n+(*p-'0');
16 p++;
17 }
18 return sign*n;
19 }
C语言: itoa
01 char *itoa(int num, char *str)
02 {
03 //remember the beginning of the string
04 char *start=str;
05 if(num<0)
06 {
07 *str++='-';
08 num=-num;
09 }
10 int x=num;
11 //length is the number of digits
12 int length=1;
13 while(x>10)
14 {
15 length*=10;
16 x/=10;
17 }
18 int digit;
19 //get the digit from high to low
20 while(length>=10)
21 {
22 digit=num/length;
23 *str++=digit+'0';
24 num=num%length;
25 length=length/10;
26 }
27 //last digit
28 if(num>=0)
29 *str++=num+'0';
30 //end of string
31 *str='\0';
32 //return the beginning of the string
33 return start;
34 }
02 {
03 //remember the beginning of the string
04 char *start=str;
05 if(num<0)
06 {
07 *str++='-';
08 num=-num;
09 }
10 int x=num;
11 //length is the number of digits
12 int length=1;
13 while(x>10)
14 {
15 length*=10;
16 x/=10;
17 }
18 int digit;
19 //get the digit from high to low
20 while(length>=10)
21 {
22 digit=num/length;
23 *str++=digit+'0';
24 num=num%length;
25 length=length/10;
26 }
27 //last digit
28 if(num>=0)
29 *str++=num+'0';
30 //end of string
31 *str='\0';
32 //return the beginning of the string
33 return start;
34 }
没有评论:
发表评论