字符串转整数以及函数atoi()的使用

转自:https://blog.csdn.net/lanzhihui_10086/article/details/39995869

atoi()函数

atoi():int atoi(const char *str );

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

str:要进行转换的字符串

返回值:每个函数返回 int 值,此值由将输入字符作为数字解析而生成。 如果该输入无法转换为该类型的值,则atoi的返回值为 0。

说明:当第一个字符不能识别为数字时,函数将停止读入输入字符串。
 

#include<iostream>
 
using namespace std;
 
int atoi_my(const char *str)
{
	int s=0;
	bool falg=false;


    //去掉字符串开头的空	
	while(*str==' ')
	{
		str++;
	}
 
    //判断字符串是正数还是负数
	if(*str=='-'||*str=='+')
	{
		if(*str=='-')
		falg=true;
		str++;
	}
 
    //开始转化
	while(*str>='0'&&*str<='9')
	{
		s=s*10+*str-'0';
		str++;
		if(s<0)
		{
			s=2147483647;
			break;
		}
	}
	return s*(falg?-1:1);
}
 
int main()
{
	char *s1="333640";
	char *s2="-12345";
	char *s3="123.3113";
	char *s4="-8362865623872387698";
	char *s5="+246653278";
 
 
	int sum1=atoi(s1);
	int sum_1=atoi_my(s1);
 
	int sum2=atoi(s2);
	int sum_2=atoi_my(s2);
 
	int sum3=atoi(s3);
	int sum_3=atoi_my(s3);
 
	int sum4=atoi(s4);
	int sum_4=atoi_my(s4);
 
	int sum5=atoi(s5);
	int sum_5=atoi_my(s5);
 
	cout<<"atoi:  :"<<sum1<<endl;
	cout<<"atoi_my:"<<sum_1<<endl;
 
	cout<<"atoi:  :"<<sum2<<endl;
	cout<<"atoi_my:"<<sum_2<<endl;
 
	cout<<"atoi:  :"<<sum3<<endl;
	cout<<"atoi_my:"<<sum_3<<endl;
 
	cout<<"atoi:  :"<<sum4<<endl;
	cout<<"atoi_my:"<<sum_4<<endl;
 
	cout<<"atoi:  :"<<sum5<<endl;
	cout<<"atoi_my:"<<sum_5<<endl;
 
	system("pause");
	return 0;
}

运行结果如下:

猜你喜欢

转载自blog.csdn.net/qq_29996285/article/details/84846295