#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
int translate_number(char *str, int size)
{
int digit = 1;
int i;
i = 0;
if (size == 1)
return str[0] - '0';
while (i < size - 1)
{
digit *= 10;
i++;
}
return (str[0] - '0') * digit + translate_number(str + 1, size - 1);
}
int white_space(char c)
{
char* h;
h = "\n\t\v\f\r ";
while (*h != '\0')
{
if (*h == c)
return (1);
h++;
}
return (0);
}
int ft_atoi(char* str)
{
int minus_count;
int number_digit;
int r;
minus_count = 0;
number_digit = 0;
r = 0;
while (white_space(*str))
str++;
while (*str == '-' || *str == '+')
{
if(*str == '-')
minus_count++;
str++;
}
while (*str >= '0' && *str <= '9')
{
number_digit++;
str++;
}
if (number_digit != 0)
r = translate_number(str - number_digit, number_digit);
if (minus_count % 2 == 0)
return r;
return -r;
}
int main(int argc, char *argv[])
{
// 테스트 케이스 1: 일반적인 숫자 변환
char str1[] = "1234";
assert(ft_atoi(str1) == 1234);
// 테스트 케이스 2: 공백과 부호 처리
char str2[] = " -1234";
assert(ft_atoi(str2) == -1234);
// 테스트 케이스 3: 여러 개의 부호 처리
char str3[] = "----++--1234";
assert(ft_atoi(str3) == 1234);
// 테스트 케이스 4: 숫자 뒤에 문자 포함
char str4[] = "1234abc";
assert(ft_atoi(str4) == 1234);
// 테스트 케이스 5: 빈 문자열
char str5[] = "";
assert(ft_atoi(str5) == 0);
// 테스트 케이스 6: 공백과 숫자만 포함
char str6[] = " 42";
assert(ft_atoi(str6) == 42);
// 테스트 케이스 8: 공백, 부호, 숫자, 그리고 문자
char str8[] = " -42abc";
assert(ft_atoi(str8) == -42);
// 테스트 케이스 9: 공백과 여러 부호 처리
char str9[] = " ++--42";
assert(ft_atoi(str9) == 42);
// 테스트 케이스 10: 공백과 여러 부호 처리, 그리고 부호 뒤에 문자
char str10[] = " ++--42abc";
assert(ft_atoi(str10) == 42);
// 테스트 케이스 11: 공백과 여러 부호 처리, 부호 뒤에 문자 그리고 숫자
char str11[] = " ++--42abc123";
assert(ft_atoi(str11) == 42);
// 테스트 케이스 12: 다양한 공백 문자 처리
char str12[] = "\t\n\v\f\r 42";
assert(ft_atoi(str12) == 42);
// 테스트 케이스 13: 공백 문자와 부호 및 숫자
char str13[] = "\t\n\v\f\r -42";
assert(ft_atoi(str13) == -42);
// assertion: 시작이 공백이 아니면 0을 반환한다
assert(ft_atoi("a12232") == 0);
assert(ft_atoi("") == 0);
assert(ft_atoi("t") == 0);
// assertion: 공백 다음에 부호가 오지 않으면 0을 반환한다
assert(ft_atoi(" \fe2323") == 0);
assert(ft_atoi(" \n\r a 2") == 0);
// assertion: 공백 다음에 부호 다음에 숫자가 오지 않으면 0을 반환한다
assert(ft_atoi(" \t +---+--a") == 0);
assert(ft_atoi(" \v +---+-- ") == 0);
// assertion: 공백 다음에 부호 다음에 숫자가 오면 합을 계산한다
assert(ft_atoi("\n\t\r\v +---+--223232") == -223232);
assert(ft_atoi("\n\t\r\v +---+--223232 ") == -223232);
assert(ft_atoi("\n\t\r\v +---+--223232a") == -223232);
// assertion: - 부호의 개수가 홀수개면 음수값이 나온다
assert(ft_atoi("\n\t\r\v +---+--223232") == -223232);
assert(ft_atoi("\n\t\r\v ++-223232") == -223232);
assert(ft_atoi("\n\t\r\v -223232") == -223232);
assert(ft_atoi("\n\t\r\v -223232-23") == -223232);
assert(ft_atoi("\n\t\r\v +223232-23") == 223232);
assert(ft_atoi("\n\t\r\v ++223232-23") == 223232);
printf("All tests passed.\n");
return 0;
}
To embed this program on your website, copy the following code and paste it into your website's HTML: