This commit is contained in:
Mathieu Maret 2021-11-08 22:30:41 +01:00
parent 29017f7f7e
commit 39cf7ab3ed
2 changed files with 29 additions and 0 deletions

View File

@ -121,6 +121,34 @@ char *itoa(long long int value, char *str, int base)
return rc; return rc;
} }
int atoi(const char *str)
{
int sign = 1, base = 0, i = 0;
// if whitespaces then ignore.
while (str[i] == ' ') {
i++;
}
// sign of number
if (str[i] == '-' || str[i] == '+') {
sign = 1 - 2 * (str[i++] == '-');
}
// checking for valid input
while (str[i] >= '0' && str[i] <= '9') {
// handling overflow test case
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
if (sign == 1)
return INT_MAX;
else
return INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
/* K&R */ /* K&R */
void reverse(char s[]) void reverse(char s[])
{ {

View File

@ -15,6 +15,7 @@ int memcmp(const void *s1, const void *s2, size_t n);
void *memcpy(void *dest, const void *src, size_t n); void *memcpy(void *dest, const void *src, size_t n);
void *memset(void *s, int c, size_t n); void *memset(void *s, int c, size_t n);
char *itoa(long long int value, char *str, int base); char *itoa(long long int value, char *str, int base);
int atoi(const char *str);
void reverse(char s[]); void reverse(char s[]);
int strlen(const char s[]); int strlen(const char s[]);
unsigned int strnlen(const char *s, size_t count); unsigned int strnlen(const char *s, size_t count);