Skip to content

Instantly share code, notes, and snippets.

@yclim95
Created June 15, 2022 00:20
Show Gist options
  • Save yclim95/d228d54d264ebc4d0a33a2a2d6fea5d0 to your computer and use it in GitHub Desktop.
Save yclim95/d228d54d264ebc4d0a33a2a2d6fea5d0 to your computer and use it in GitHub Desktop.
ft_atoi() in c
#include <stdio.h>
#include <stdlib.h>

int	ft_isdigit(int c)
{
	return (c >= '0' && c <= '9');
}

int	ft_atoi(const char *nptr)
{
	int	num;
	int	sign;

	num = 0;
	sign = 1;
	while (*nptr == ' ' || (*nptr >= '\t' && *nptr <= '\r'))
		nptr++;
	if (*nptr == '-' || *nptr == '+')
	{
	    if (*nptr++ == '-')
		    sign = -1;
	}
	while (ft_isdigit(*nptr))
	{
		num = (*nptr - '0') + (num * 10);
		nptr++;
	}
	return (num * sign);
}

int main()
{
    printf("123: %d\n", ft_atoi("123"));
    printf("-123: %d\n", ft_atoi("-123"));
    printf("0: %d\n", ft_atoi("0"));
    printf("    -123: %d\n", ft_atoi("    -123"));
    printf("   +--123: %d\n", ft_atoi("   +--123"));
    printf("   +--123++--: %d\n", ft_atoi("   +--123++--"));
    printf("atoi -    +--123: %d\n", atoi("   +--123"));
    printf("atoi -    +-123: %d\n", atoi("   +-123"));
    printf("atoi   +--123++--: %d\n", atoi("   +--123++--"));

    return 0;
}
123: 123
-123: -123
0: 0
    -123: -123
   +--123: 0
   +--123++--: 0
atoi -    +--123: 0
atoi -    +-123: 0
atoi   +--123++--: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment