C语言杂记

  • strcmp函数是可以和int数字进行比较的
    1   int ch[] = {97, 97, 97, 0};
    
    2     puts(ch);
    
    3     if (strcmp("AAA", ch)) {
    
    4         printf("real?true!");
    
    5     }

     

  • 实现stdlib::atoi函数(字符串转数字) 
     1 /**
    
     2 * 实现stdlib::atoi函数(字符串转数字)
    
     3 */
    
     4 int myatoi(const char *strp) {
    
     5 
    
     6     //用来存放最终值
    
     7     int result = 0;
    
     8 
    
     9     int sign = 1;
    
    10 
    
    11     //跳过前面的空白字符
    
    12     while (*strp == ' ' || *strp == '\t' || *strp == '\n' || *strp == '\f' || *strp == '\b' || *strp == '\r')
    
    13         ++strp;
    
    14 
    
    15     if (*strp == '-') {
    
    16         sign = -1;
    
    17         ++strp;
    
    18     } else if (*strp == '+') {
    
    19         sign = 1;
    
    20         ++strp;
    
    21     }
    
    22 
    
    23 
    
    24     while ('0' <= *strp && *strp <= '9') {
    
    25 
    
    26         short c = (short) (*strp++ - '0');
    
    27 
    
    28         //当前数字乘以乘数,得出补全0的高位
    
    29         result = 10 * result + c;
    
    30 
    
    31 
    
    32     }
    
    33     result *= sign;
    
    34 
    
    35     return result;
    
    36 }

     


  •  下面是源代码,仔细看了一下,然后修改修改。

     1 isspace(int x)
    
     2 {
    
     3  if(x==' '||x=='\t'||x=='\n'||x=='\f'||x=='\b'||x=='\r')
    
     4   return 1;
    
     5  else  
    
     6   return 0;
    
     7 }
    
     8 isdigit(int x)
    
     9 {
    
    10  if(x<='9'&&x>='0')         
    
    11   return 1;x` 
    
    12  else 
    
    13   return 0;
    
    14 
    
    15 }
    
    16 int atoi(const char *nptr)
    
    17 {
    
    18         int c;              /* current char */
    
    19         int total;         /* current total */
    
    20         int sign;           /* if '-', then negative, otherwise positive */
    
    21 
    
    22         /* skip whitespace */
    
    23         while ( isspace((int)(unsigned char)*nptr) )
    
    24             ++nptr;
    
    25 
    
    26         c = (int)(unsigned char)*nptr++;
    
    27         sign = c;           /* save sign indication */
    
    28         if (c == '-' || c == '+')
    
    29             c = (int)(unsigned char)*nptr++;    /* skip sign */
    
    30 
    
    31         total = 0;
    
    32 
    
    33         while (isdigit(c)) {
    
    34             total = 10 * total + (c - '0');     /* accumulate digit */
    
    35             c = (int)(unsigned char)*nptr++;    /* get next char */
    
    36         }
    
    37 
    
    38         if (sign == '-')
    
    39             return -total;
    
    40         else
    
    41             return total;   /* return result, negated if necessary */
    
    42 } 

你可能感兴趣的:(C语言)