atoi.c 841 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* Assignment name : ft_atoi
  2. Expected files : ft_atoi.c
  3. Allowed functions: None
  4. --------------------------------------------------------------------------------
  5. Write a function that converts the string argument str to an integer (type int)
  6. and returns it.
  7. It works much like the standard atoi(const char *str) function, see the man.
  8. Your function must be declared as follows:
  9. int ft_atoi(const char *str); */
  10. #include <unistd.h>
  11. #include <stdio.h>
  12. int ft_atoi(const char *str)
  13. {
  14. int i;
  15. int cp;
  16. int minus;
  17. i = 0;
  18. minus = 0;
  19. while (str[i])
  20. {
  21. if (str[i] == 45)
  22. {
  23. minus++;
  24. i++;
  25. }
  26. else if (str[i] > 47 && str[i] < 58)
  27. {
  28. cp = cp * 10 + str[i] - '0';
  29. i++;
  30. }
  31. else
  32. i++;
  33. }
  34. if (minus % 2 == 1)
  35. cp = -cp;
  36. return (cp);
  37. }
  38. int main(void)
  39. {
  40. printf("%d\n", ft_atoi(" kjh-123007450dfgfeh2"));
  41. }