每日一练:将字符串转成整数

解题思路:

  将字符串str中的每个字符通过ascll码转换成对应的数字,定义一个计数器num,每转换一次num*10,再加上当前字符转成的数字。

字符串在转整数的时候要注意特殊情况:当第一个字符为+/-/字母/空格时。

#include<stdio.h>
#include<windows.h>
#include<assert.h>
enum en
{
	EROR,      //0
	OK    //1
};
enum en st = EROR;
int paraInt(char *dest)
{
	assert(dest);
	long long sum = 0;          //用sum来保存得到的整数
	int flag = 1;
	if (*dest == '+')           //第一个字符为+的情况
		dest ++;
	if (*dest == '-')            //第一个字符为-的情况
	{
		flag = -flag;
		dest++;
	}
	if (isspace(*dest))          //第一个字符是空格的情况
	{
		dest++;
	}
	while (isdigit(*dest)){                //判断字符串中是否有数字,有时为ture
		if (*dest >= '0'&&*dest <= '9')
			sum = sum * 10 +flag*(*dest- '0');
		if (sum<INT_MAX&&sum>INT_MIN)      //INT_MAX整数int型最大值,INT_MINint型最小值
			sum = (int)sum;
		st = OK;
		dest++;
	}
	return sum;
}
int main(){
	char str[] = " 1236666644";
	int ret = paraInt(str);
	if (st)                           //当st为OK的时候输出
	{
		printf("%d\n", ret);
	}
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_41889292/article/details/80609862