C语言atoi()函数:将字符串转换成int(整数)

头文件:#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 转换成数字后相加。

#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int i;
    char buffer[256];
    printf ("Enter a number: ");
    fgets (buffer, 256, stdin);
    i = atoi (buffer);
    printf ("The value entered is %d.", i);
    system("pause");
    return 0;
}

 

posted @ 2015-12-04 00:59  X-POWER  阅读(3410)  评论(0编辑  收藏  举报