zoukankan      html  css  js  c++  java
  • 《C库 — 字符串和整型数相互转换函数atoi和itoa》

    https://www.cnblogs.com/bluestorm/p/3168719.html

    1.atoi函数原型

    int atoi(const char *nptr);
    

      atoi (表示 ascii to integer)是把字符串转换成整形数的一个函数。int atoi(const char *nptr) 函数会扫描参数 nptr字符串,会跳过前面的空白字符(例如空格,tab缩进)等。如果 nptr不能转换成 int 或者 nptr为空字符串,那么将返回0。

      特别注意,该函数要求被转换的字符串是按十进制数理解的。atoi输入的字符串对应数字存在大小限制(与int类型大小有关),若其过大可能报错-1。

      注意:当有数字字符和其他字符混合时,需要将两个分离出来。

    2.例子

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void)
    {
        int n;
        char *str = "12345.67";
        n = atoi(str);
        printf("n=%d
    ",n);
        return 0;
    }
    

      输出:n = 12345

      说明当检测到不是数字字符的时候,就直接返回。

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void)
    {
        int n;
        char *str = "pp12345.67";
        n = atoi(str);
        printf("n=%d
    ",n);
        return 0;
    }
    

      输出:n = 0 

    3.itoa函数原型

    char *itoa( int value, char *string,int radix);
    

      value:欲转换的数据。

      string:目标字符串的地址。

      radix:转换后的进制数,可以是10进制、16进制等。

    4.实例

    #include <stdlib.h>
    #include <stdio.h>
    int main(void)
    {
        int number = 12345;
        char string[32];
        itoa(number, string, 10);
        printf("integer = %d string = %s
    ", number, string);
        return 0;
    }
    

      itoa 并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。

  • 相关阅读:
    suse系统FTP问题
    Oracle SQL编写注意事项
    EXP-00056: ORACLE error 6550 encountered报错;
    Linux 单网卡多 IP 的配置方法
    Authorized users only. All activity may be monitored and reported.
    使用jconsole检测linux服务器
    Suse系统用户不能登录报错
    性能测试介绍
    判断浏览器是否是手机端
    JSONP 跨域请求
  • 原文地址:https://www.cnblogs.com/zhuangquan/p/12572730.html
Copyright © 2011-2022 走看看