数据类型之间的转化

atoi

   C语言库函数 名: atoi
  功 能: 把字符串转换成 整型 数.
  名字来源:array to integer 的缩写.
  原型: int atoi(const char *nptr);
  函数说明: 参数nptr字符串,如果 第一个非空格字符 不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回 整型 数。
  头文件: #include < stdlib.h >
  程序例:
  1)
  #include <stdlib.h>
  #include <stdio.h>
  int main(void)
  {
  int n;
  char *str = "12345.67";
  n = atoi(str);
  printf("string = %s integer = %d\n", str, n);
  return 0;
  }
  执行结果
  string = 12345.67 integer = 12345
  2)
  #include <stdlib.h>
  #include <stdio.h>
  int main()
  {
  char a&#91;&#93; = "-100" ;
  char b&#91;&#93; = "123" ;
  int c ;
  c = atoi( a ) + atoi( b ) ;
  printf("c = %d\n", c) ;
  return 0;
  }
  执行结果
  c = 23
  简单的实现atoi函数 源代码 :
  #include <cctype>
  int my_atoi(const char* p){
  assert(p != NULL);
  bool neg_flag = false;// 符号标记
  int res = 0;// 结果
  if(p&#91;0&#93; == '+' || p&#91;0&#93; == '-')
  neg_flag = (*p++ != '+');
  while(isdigit(*p)) res = res*10 + (*p++ - '0');
  return neg_flag ?0 -res : res;
  }
  

atof

  1. 函数名: atof
  功 能: 把字符串转换成浮点数
  名字来源:array to floating point numbers 的缩写
  用 法: double atof(const char *nptr);
  程序例:
  #include < stdlib.h >
  #include <stdio.h>
  int main()
  {
  float f;
  char *str = "12345.67";
  f = atof(str);
  printf("string = %s float = %f\n", str, f);
  return 0;
  }
  2. atof(将字串转换成 浮点型 数) 
  相关函数 atoi , atol , strtod , strtol , strtoul 
  表头文件 #include <stdlib.h>
  定义函数 double atof(const char *nptr);
  函数说明 atof()会扫描参数nptr 字符 串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分,如123.456或123e-2。
  返回值 返回转换后的 浮点型 数。
  附加说明 atof()与使用 strtod (nptr,(char**)NULL)结果相同。
  范例 /* 将字符串a 与字符串b转换成数字后相加*/
  #include<stdlib.h>
  int main()
  {
  char *a="-100.23";
  char *b="200e-2";
  float c;
  c=atof(a)+atof(b);
  printf(“c=%.2f\n”,c);
  return 0;
  }
  执行 c=-98.23
  注:此文的事例摘录于金山词典的汉语频道。
原文地址:https://www.cnblogs.com/huxianlu/p/3034822.html