C语言---整型字符串转换

C语言提供了几个标准库函数,能够将随意类型(整型、长整型、浮点型等)的数字转换为字符串。下面是用itoa()函数将整数转 换为字符串的一个样例:

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

    void main (void)
    {
    int num = 100;
    char str[25];
    itoa(num, str, 10);
    printf("The number ’num’ is %d and the string ’str’ is %s. /n" ,
    num, str);
    }

    itoa()函数有3个參数:第一个參数是要转换的数字,第二个參数是要写入转换结果的目标字符串,第三个參数是转移数字时所用 的基数。在上例中,转换基数为10。10:十进制;2:二进制...
    itoa并非一个标准的C函数,它是Windows特有的,假设要写跨平台的程序,请用sprintf。
    是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,使用方法跟printf相似:

    char str[255];
    sprintf(str, "%x", 100); //将100转为16进制表示的字符串。

函数名: atol

  功 能: 把字符串转换成长整型数

  用 法: long atol(const char *nptr);

  程序例:

#include <stdlib.h>

  #include <stdio.h>

  int main(void)

  {

  long l;

  char *str = "98765432";

  l = atol(str); /* 原来为l = atol(lstr); */

  printf("string = %s integer = %ld/n", str, l);

  return(0);

  }

  atol(将字符串转换成长整型数)

  相关函数 atof,atoi,strtod,strtol,strtoul

  表头文件 #include<stdlib.h>

  定义函数 long atol(const char *nptr);

  函数说明 atol()会扫描參数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才開始做转换,而再遇到非数字或字符串结束时('/0')才结束转换,并将结果返回。

  返回值 返回转换后的长整型数。

  附加说明 atol()与使用strtol(nptr,(char**)NULL,10);结果同样。

  范例 /*将字符串a与字符串b转换成数字后相加*/

  #include<stdlib.h>

  main()

  {

  char a[]=”1000000000”;

  char b[]=” 234567890”;

  long c;

  c=atol(a)+atol(b);

  printf(“c=%d/n”,c);

  }

  运行 c=1234567890

原文地址:https://www.cnblogs.com/zfyouxi/p/4040160.html