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 }

     


  •  下面是源代碼,仔細看了一下,而後修改修改。git

     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 }
相關文章
相關標籤/搜索