strtol,strtoul,strtod

来源:互联网 发布:传奇推广员 知乎 编辑:程序博客网 时间:2024/06/05 20:46
Technorati 标签: strtol,strtoul,strtod

函数原型:

long int strtol ( const char * str, char ** endptr, int base );
unsigned long int strtoul ( const char * str, char ** endptr, int base );
double strtod ( const char * str, char ** endptr );
 
这几个函数从str指向的字符开始转化,忽略掉前面的空格,遇到错误无法转换的字符则返回,如果endptr不为空,则将该字符存储在endptr里。
对前两个函数,base则表示其进制。
想到之前的一篇笔记:http://www.cppblog.com/izualzhy/archive/2012/07/09/182456.html
需要将”0xE4”转到E4(1个字节)
可以简单的这么写了:
    char str[] = "E4";    int a;    a = strtol(str,NULL,16);
看个详细的例子:
/* * ===================================================================================== *       Filename:  strtodata.c *    Description:  string to long/unsigned long/double * *        Version:  1.0 *        Created:  08/16/2012 07:30:17 PM * *         Author:  zhy (), izualzhy@163.com * ===================================================================================== */#include <stdio.h>#include <stdlib.h>int main(){    char numbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";    char *pEnd;    long int li1,li2,li3,li4;    li1 = strtol(numbers, &pEnd, 10);    li2 = strtol(pEnd, &pEnd, 16);    li3 = strtol(pEnd, &pEnd, 2);    li4 = strtol(pEnd, NULL, 0);    printf("The decimal equivalents are: %ld, %ld, %ld, %ld.\n",li1,li2,li3,li4);    char digits[] = "365.24   29.53 -1.23456";        double d1,d2,d3;    d1 = strtod(digits, &pEnd);    printf("%c\n", *pEnd);    d2 = strtod(pEnd, &pEnd);    d3 = strtod(pEnd, NULL);    printf("The moon completes %f/%f orbits per Earth yes.%f\n",d1,d2,d3);    return 0;}

运行结果:

The decimal equivalents are: 2001, 6340800, -3624224, 7340031.
 
The moon completes 365.240000/29.530000 orbits per Earth yes.-1.234560




====================================================================================================================================

/*
 * =====================================================================================
 *
 *       Filename:  strtok.c
 *
 *    Description:  j
 *
 *        Version:  1.0
 *        Created:  2013年03月01日 18时34分13秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <string.h>


void split_str_to_intArray(char *pSeparator, char *pStr, int *pData)
{
    char *pbuf;
    int cnt = 0;


    memset( pData, 0, sizeof( pData ) );


    pbuf = strtok( pStr, pSeparator );
    while( NULL != pbuf )
    {
       pData[ cnt ] = strtol( pbuf, NULL, 10); 
       pbuf = strtok( NULL, pSeparator );
       cnt ++;
    }


    return;
}


int main(int argc, const char *argv[])
{
    char a[] = "1,,,4..24..1.4.6.2435,2,34,234.3 414*";
    int b[10];
    int i;


    memset( b, 0, sizeof( b ) );
    split_str_to_intArray( ",. *", a, b );


    for( i = 0; i < 10; i++)
        printf("%d\n", b[i]);


    return 0;
}

原创粉丝点击