함수 만들기 - atoi

nhwang·2021년 12월 9일
0

구현


int	ft_checknum(char str)
{
	if ((48 <= str) && (str <= 57))
		return (1);
	return (0);
}

int	ft_checksp(char str)
{
	if ((str == ' ') || ((9 <= str) && (str <= 13)))
		return (1);
	else
		return (0);
}

int	ft_checkbuho(char str)
{
	if (str == '+')
		return (1);
	if (str == '-')
		return (-1);
	else
		return (0);
}

int	ft_atoi(const char *s)
{
	const char	*st;
	int			buho;
	int			num;

	num = 0;
	st = s;
	buho = 1;
	while (*st && ft_checksp(*st))
	{
		st++;
	}
	if (*st && (ft_checkbuho(*st) != 0))
	{
		buho = ft_checkbuho(*st);
		st++;
	}
	while (*st && ft_checknum(*st))
	{
		num = (num * 10) + ((int)(*st) - 48);
		st++;
	}
	return (num * buho);
}

반환
정수형으로 바뀐 부분

예외처리
공백문자가 처음에 오는 경우 여러개까지 스킵할 수 있다.
부호는 공백문자 전에 오는 경우에는 바로 숫자가 와야한다. (- 123) >>> 0 리턴 /// (-123) >>> -123 리턴
이후 숫자가 끝나면 뒤에 공백이 온 다음 다시 숫자가 시작되더라도 처음의 숫자만 받아낸다.

유용해보이는 테크닉
num = (num 10) + ((int)(st) - 48);

profile
42Seoul

0개의 댓글