atoi() 函数用来将字符串转换成整数(int)

来源:互联网 发布:网络上刘皇叔是什么梗 编辑:程序博客网 时间:2024/04/30 03:29
头文件:#include <stdlib.h>

atoi() 函数用来将字符串转换成整数(int),其原型为:
int atoi (const char * str);

【函数说明】atoi() 函数会扫描参数 str 字符串,跳过前面的空白字符(例如空格,tab缩进等,可以通过 isspace() 函数来检测),直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。

【返回值】返回转换后的整型数;如果 str 不能转换成 int 或者 str 为空字符串,那么将返回 0。

温馨提示:ANSI C 规范定义了 stof()atoi()atol()strtod()strtol()strtoul() 共6个可以将字符串转换为数字的函数,大家可以对比学习。另外在 C99 / C++11 规范中又新增了5个函数,分别是 atoll()、strtof()、strtold()、strtoll()、strtoull(),在此不做介绍,请大家自行学习。

范例:将字符串a 与字符串b 转换成数字后相加。
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main ()
  4. {
  5.     int i;
  6.     char buffer[256];
  7.     printf ("Enter a number: ");
  8.     fgets (buffer, 256, stdin);
  9.     i = atoi (buffer);
  10.     printf ("The value entered is %d.", i);
  11.     system("pause");
  12.     return 0;
  13. }
执行结果:
Enter a number: 233cyuyan
The value entered is 233.
0 0
原创粉丝点击