字符串面试题:将字符串转换为整数

在上一篇博文中介绍了如何实现将整数转换为字符串,这里在介绍一个将字符串转换为整数的实现方法。

 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 

 4 int isspace(int x);

 5 int isspace(int x);

 6 int my_atoi(const char *nptr);

 7 

 8 int main(void)

 9 {

10     char str[33];

11     int  num;

12     scanf("%s", str);

13     num = my_atoi(str);

14     printf("Ans: %d\n", num);

15 

16     return 0;

17 }

18 

19 int isspace(int x)

20 {

21     if(x==' ' || x=='\t' || x=='\n' || x=='\f' || x=='\b' || x=='\r')

22         return 1;

23     else  

24         return 0;

25 }

26 

27 int isdigit(int x)

28 {

29     if(x<='9' && x>='0')         

30         return 1; 

31     else 

32         return 0;

33 }

34 

35 int my_atoi(const char *nptr)

36 {

37     int c;             /* current char */

38     int total;         /* current total */

39     int sign;          /* if '-', then negative, otherwise positive */

40 

41     /* skip whitespace */

42     while ( isspace((int)(unsigned char)*nptr) )

43         ++nptr;

44 

45     // 读取第一个非空白符

46     c = (int)(unsigned char)*nptr++;

47     sign = c;          /* save sign indication */

48     if (c == '-' || c == '+')

49         c = (int)(unsigned char)*nptr++;    /* skip sign */

50 

51     total = 0;

52 

53     while (isdigit(c)) {

54         total = 10 * total + (c - '0');     /* accumulate digit */

55         c = (int)(unsigned char)*nptr++;    /* get next char */

56     }

57 

58     if (sign == '-')

59         return -total;

60     else

61         return total;   /* return result, negated if necessary */

62 }

 

你可能感兴趣的:(字符串)