C/C++ 字符串与数字相互转化方法小结

1. 字符串 --> 数字

ato<xxx>: atoi(), atol(), atoll(), atof()
strto<xxx>: strtol(), strtoul(), strtod()
strto<xxx> 是 ato<xxx> 的升级版:
(1) strto<xxx> 支持转化成多种进制
(2) ato<xxx> 对错误情况的处理很不完善, strto<xxx> 对完善了错误处理

#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <errno.h>

int
main(int argc, char *argv[])
{
    int base;
    char *endptr, *str;
    long val;

    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    str = argv[1];
    base = (argc > 2) ? atoi(argv[2]) : 10;

    errno = 0;  /* To distinguish success/failure after call */
    val = strtol(str, &endptr, base);

    /* Check for various possible errors */
    if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
           || (errno != 0 && val == 0))
    {
        perror("strtol");
        exit(EXIT_FAILURE);
    }

    if (endptr == str)
    {
        fprintf(stderr, "No digits were found\n");
        exit(EXIT_FAILURE);
    }

    /* If we got here, strtol() successfully parsed a number */
    printf("strtol() returned %ld\n", val);

    if (*endptr != '\0')    /* Not necessarily an error... */
        printf("Further characters after number: %s\n", endptr);

    exit(EXIT_SUCCESS);
}

http://man7.org/linux/man-pages/man3/strtoll.3.html

2. 数字 --> 字符串

(1) sprintf()
(2) ostringstream or stringstream:  http://blog.csdn.net/duyiwuer2009/article/details/23165627



你可能感兴趣的:(C/C++ 字符串与数字相互转化方法小结)