zoukankan      html  css  js  c++  java
  • strtod-strtod, 字符串 转 数字 函数



    strtod()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,到出现非数字或字符串结束时('')才结束转换,并将结果返回。若endptr不为

    NULL,则会将遇到不合条件而终止的nptr中的字符指针由endptr传回。参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分。如123.456或123e-2。


    #include<stdlib.h>
    #include<stdio.h>
    void main()
    {
        char *endptr;
        char a[] = "12345.6789";
        char b[] = "1234.567qwer";
        char c[] = "-232.23e4";
        printf( "a=%lf ", strtod(a,NULL) );
        printf( "b=%lf ", strtod(b,&endptr) );
        printf( "endptr=%s ", endptr );
        printf( "c=%lf ", strtod(c,NULL) );
    }
    执行:


    a=12345.678900
    b=1234.567000
    endptr=qwer
    c=-2322300.000000



    strtol函数

     参数base范围从2至36,或0。参数base代表采用的进制方式,如base值为10则采用10进制,若base值为16则采用16进制等。当base值为0时则是采用10进制做转换,但遇到如’0x’前置字符则会使用16进制做转换、遇到’0’前置字符而不是’0x’的时候会使用8进制做转换。
    一开始strtol()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,再遇到非数字或字符串结束时('')结束转换,并将结果返回。若参数endptr不为NULL,则会将遇到不合条件而终止的nptr中的字符指针由endptr返回;若参数endptr为NULL,则会不返回非法字符串。
    #include<stdlib.h>
    #include<stdio.h>
    voidmain(void)
    {
    char*string,*stopstring;
    doublex;
    intbase;
    longl;
    unsignedlongul;
    string="3.1415926Thisstoppedit";
    x=strtod(string,&stopstring);
    printf("string=%s ",string);
    printf("strtod=%f ",x);
    printf("Stoppedscanat:%s ",stopstring);
    string="-10110134932Thisstoppedit";
    l=strtol(string,&stopstring,10);
    printf("string=%s ",string);
    printf("strtol=%ld ",l);
    printf("Stoppedscanat:%s ",stopstring);
    string="10110134932";
    printf("string=%s ",string);
    /*Convertstringusingbase2,4,and8:*/
    for(base=2;base<=8;base*=2)
    {
    /*Convertthestring:*/
    ul=strtoul(string,&stopstring,base);
    printf("strtol=%ld(base%d) ",ul,base);
    printf("Stoppedscanat:%s ",stopstring);
    }
    }
    string=3.1415926Thisstoppedit
    strtod=3.141593
    Stoppedscanat:Thisstoppedit
    string=-10110134932Thisstoppedit
    strtol=-2147483648
    Stoppedscanat:Thisstoppedit
    string=10110134932
    strtol=45(base2)
    Stoppedscanat:34932
    strtol=4423(base4)
    Stoppedscanat:4932
    strtol=2134108(base8)
    Stoppedscanat:932





  • 相关阅读:
    112th LeetCode Weekly Contest Validate Stack Sequences
    112th LeetCode Weekly Contest Minimum Increment to Make Array Unique
    C# 有关系统音量的操作
    C# 关于时区的操作
    WordPress 设置GeoIP数据库目录权限时错误解决方案
    AtCoder Beginner Contest 113 C
    AtCoder Beginner Contest 113 B
    AtCoder Beginner Contest 113 A
    将Tomcat注册为Windows服务
    常用的调试方法
  • 原文地址:https://www.cnblogs.com/roger0212/p/4436702.html
Copyright © 2011-2022 走看看