ft_atoi
Subject
ATOI(3) (simplified)
NAME
atoi -- convert ASCII string to integer
SYNOPSIS
int atoi(const char *str);
DESCRIPTION
The atoi() function converts the initial portion of the string pointed to by str to int representation.
Understandable explanation
The atoi()
function converts a string to its int
representation.
Some things that the atoi()
function does are not clearly said in the man. I'll quickly list them here.
The string passed as parameter may begin with an arbitrary number of whitespaces as determined by
isspace(3)
After the arbitrary number of whitespaces, there can be one single optional '+' or '-' sign
The remainder of the string will be converted to an int, stopping at the first character which is not a valid digit in the given base (in our case we only need to manage base 10, so the valid digits are 0-9)
I talked about the isspace(3)
function, what is that function ? It works the same way as the isdigit
, isalpha
, etc. but returning a non-zero value when the character is one of the following
To make it easier, will be coding the isspace(3)
function as a static helper function for our atoi(3)
function.
Hints
int ft_atoi(const char *str)
{
while (/* character isspace */)
/* advance in the string */
if (/* character is + and next character is not - */)
/* advance in the string */
if (/* character is - */)
/* save the sign as negative */
while (/* there is something in the string and that is a digit 0-9 */)
/* convert the current digit value to int value */
/* don't overwrite what we already converted */
/* multiply the int result by the sign */
return (/* result */);
}
static int ft_isspace(int c)
{
if (/* c is one of the whitespace characters */)
return (/* non-zero value of your choice */);
return (0);
}
Commented solution
Last updated
Was this helpful?