zoukankan      html  css  js  c++  java
  • C语言数字与字符串转换 atoi()函数、itoa()函数、sprintf()函数

    在编程中经常需要用到数字与字符串的转换,下面就总结一下。

    1.atoi()

      C/C++标准库函数,用于字符串到整数的转换。

      函数原型:int atoi (const char * str);

    1 #include <stdio.h>
    2 #include <stdlib.h>
    3 int main ()
    4 {
    5     char *numchars="1234";
    6     int num=atoi(numchars);
    7     printf("%d
    ",num);
    8     return 0;
    9 }

      另外C/C++还提供的标准库函数有:

      (1)long int atol ( const char * str );  

      (2)double atof (const char* str);

    2.itoa()

      不是C/C++标准库函数,用于整数到字符串的转换。

      函数原型:char *itoa(int value, char *string, int radix);

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 int main ()
     4 {
     5     int num=1234;
     6     int radix=8;
     7     char res[20];
     8     itoa(num,res,radix);
     9     printf("%d(10)=%s(%d)
    ",num,res,radix);    //输出:1234(10)=2322(8)
    10     return 0;
    11 }

    3.sprintf()

      C/C++标准库函数,可以用于整数到字符串的转换。

      sprintf:Write formatted data to string。

      sprintf作用是将printf的输出结果保存在字符串数组中。

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 int main ()
     4 {
     5     int num=1234;
     6     char res[20];
     7     sprintf(res,"%0o",num);
     8     printf("%s
    ",res); //8进制输出:2322
     9 
    10     sprintf(res,"%0x",num);
    11     printf("%s
    ",res); //16进制输出:4d2
    12     return 0;
    13 }

      

  • 相关阅读:
    七牛云上传博客
    .net 导入Excel
    liunx ln -s 软连接
    dos2unix 命令
    x-csrf-token
    设置git 不提交 修改权限的文件
    nginx 启动、重启、关闭
    命令行导入mysql数据
    mongo 相关命令
    laravel 安装完成后安装 vendor 目录
  • 原文地址:https://www.cnblogs.com/xudong-bupt/p/3479350.html
Copyright © 2011-2022 走看看