搜索此博客

2013年2月13日星期三

Implementation of getline, atoi and itoa

In this blog, I introduce some implementation of the std functions in C.

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 }

atoi(): convert the character string representation of a number to the integer representation. Remember the sign, and remember to skip the spaces in front of the string.

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 }


itoa(): the opposite of atoi(),convert the integer representation of a number to its character string representation. It's a little more tricky than atoi. You need to start from the beginning of the number. Get the last digit of a number is easy, we just mod 10. How to get the digit at the very beginning of a number? We need to know how many digits this number have first. I use length to represent it. To get the length, you need to keep multipling 10 (line 12 - 17). The very beginning digit is obtained from dividing the number by length, and the number becomes itself mod length. Then you shrink length by 1 less digit. For example, you have a number 123, length is 100. you divide it by 100, and you get 1. Then your length becomes 10, and your number becomes 23. Then you divide 23 by 10, you get 2. (line 20 - 26)In the end you have a remaining number 3, just append it to the end of the string (line 28 - 29). 

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 }

没有评论:

发表评论