zoukankan      html  css  js  c++  java
  • B00005 函数atoi()(去空格,带符号)

    这是一个通用的基础程序,将数字字符串转换为整型数。

    这个程序会去掉字符串开始的空格,并且能够转换带符号的整数。

    该程序来自K&C的《C程序设计语言》一书。

    程序如下:

    /* 带符号的atoi,跳过前面的空格 */
    
    #include <stdio.h>
    
    #include <ctype.h>
    
    int atoi(char s[])
    {
        int n;
        int i;
        int sign;
    
        for(i=0;isspace(s[i]);i++)
            ;
        sign = (s[i]=='-')? -1:1;
        if(s[i] =='+'||s[i]=='-')
            i++;
        for(n=0;isdigit(s[i]);i++)
            n = n*10 + s[i]-'0';
    
        n = sign * n;
    
        return n;
    }
    
    int main(void)
    {
        printf("%d
    ", atoi(" 356"));
        printf("%d
    ", atoi(" 1234567"));
    
        printf("%d
    ", atoi(" -356"));
        printf("%d
    ", atoi(" -1234567"));
    
        return 0;
    }
    关键代码:

    #include <ctype.h>
    
    int atoi(char s[])
    {
        int n;
        int i;
        int sign;
    
        for(i=0;isspace(s[i]);i++)
            ;
        sign = (s[i]=='-')? -1:1;
        if(s[i] =='+'||s[i]=='-')
            i++;
        for(n=0;isdigit(s[i]);i++)
            n = n*10 + s[i]-'0';
    
        n = sign * n;
    
        return n;
    }

    运行结果:

    356
    1234567
    -356
    -1234567


  • 相关阅读:
    es6
    vue-router
    vue-lazyload
    java-number2
    echart事件
    weui了解
    java-number
    Java判断语句
    java 循环控制
    The access type for the readers of the blog.
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564859.html
Copyright © 2011-2022 走看看