ft_atoi

jaehlee·2025년 4월 25일

Libft

목록 보기
7/26

1. ft_atoi란?


문자열 str을 정수로 만들어주는 함수이다.

2. 함수 프로토타입

int	ft_atoi(const char *str)

3. 함수 구현

#include "libft.h"

static int	is_space(char c)
{
	if (c == '\n' || c == '\t' || c == '\r' || c == '\f' || c == '\v'
		|| c == ' ')
		return (1);
	return (0);
}

int	ft_atoi(const char *str)
{
	int	i;
	int	neg;

	i = 0;
	neg = 0;
	while (is_space(*str))
		str++;
	if (*str == '-' || *str == '+')
	{
		if (*str == '-')
			neg++;
		str++;
	}
	while (*str >= '0' && *str <= '9')
	{
		i = i * 10 + (*str - '0');
		str++;
	}
	if (neg % 2 != 0)
		i = i * -1;
	return (i);
}

is_space로 문자열의 시작공백을 없앤 후 변환

사용예시

#include <stdio.h>

int	main(void)
{
	printf("%d\n", ft_atoi("   -42"));     // -42
	printf("%d\n", ft_atoi("4193abc"));    // 4193
	printf("%d\n", ft_atoi("+1234"));      // 1234
	printf("%d\n", ft_atoi("  \t\v\n42")); // 42
	return (0);
}
profile
공부하는 개발자

0개의 댓글