atoi函数的讲解

来源:互联网 发布:网络信息安全 电子书 编辑:程序博客网 时间:2024/05/21 05:39
学习C语言的时候,用来练习用的,现在分享给大家,希望大家能够喜欢。
希望能和大家共同学习C语言及c++,有不足的地方,请大家多多指点。


今天对atoi函数的讲解
atoi(表示ascil to integer)是把字符串转换成整型数的一个函数,应用在计算机程序和办公软件中,atoi()
函数会扫描参数nptr字符串,跳过前面的空白字符,直到遇到数字和正负号才开始做转换,而在遇到非数字和'\0'
才结束,如果nptr不能转换成int或者nptr为空字符,就返回0。


函数原型:
头文件 #include <stdlib.h>
int atoi(const char *nptr);

功能: 实现将字符串(“1234”)转化为数字。

/* 该例子只能实现正数的转换 */
#include <stdio.h>
#include <stdlib.h>
int myatoi(const char *pstr){
int n = 0;
while(*pstr){
if( ('0' <= *pstr) && (*pstr <= '9' )){
n = n * 10 + (*pstr - '0');
}
else{
return n;
}
++pstr;
}
return n;
}


int main(int argc, char *argv[]){
if(argc != 2){
printf("Usage: %s number\n", argv[0]);
return -1;
}

printf("结果 = %d\n", myatoi(argv[1]));
}

原创粉丝点击