mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
add atoi that convert string to integer
This commit is contained in:
parent
7c815b86b2
commit
32c725603f
40
conversions/c_atoi_str_to_integer.c
Normal file
40
conversions/c_atoi_str_to_integer.c
Normal file
@ -0,0 +1,40 @@
|
||||
#include <stdio.h>
|
||||
|
||||
// recoding the original atoi function in stdlib.h
|
||||
int c_atoi(char *str)
|
||||
{
|
||||
int i;
|
||||
int sign;
|
||||
long value;
|
||||
long prev;
|
||||
|
||||
i = 0;
|
||||
sign = 1;
|
||||
value = 0;
|
||||
// skip wait spaces
|
||||
while (((str[i] <= 13 && str[i] >= 9) || str[i] == 32) && str[i] != '\0')
|
||||
i++;
|
||||
// store the sign
|
||||
if (str[i] == '-' || str[i] == '+')
|
||||
(str[i++] == '-') ? sign = -1 : 1;
|
||||
// convert char by char to an int value
|
||||
while (str[i] >= 48 && str[i] <= 57 && str[i] != '\0')
|
||||
{
|
||||
prev = value;
|
||||
value = value * 10 + sign * (str[i] - '0');
|
||||
// manage the overflow
|
||||
if (sign == 1 && prev > value)
|
||||
return (-1);
|
||||
else if (sign == -1 && prev < value)
|
||||
return (0);
|
||||
i++;
|
||||
}
|
||||
return (value);
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
// Test
|
||||
printf("%d\n", c_atoi("-234"));
|
||||
}
|
Loading…
Reference in New Issue
Block a user