I have a helper function in my program that is
long parse_int (char * cp, int * i)
{
/*
Helper function
cp: Pointer to a character array that is a base-10 string representation of an integer
i: Pointer to an integer which will store the output of the parsing of cp
Returns the number of characters parsed.
*/
long n = 0;
*i = 0;
while (cp!= '\0')
{
char c = *cp;
long k = index_of(digits, c);
if (k > -1)
{
n = n * 10 + k;
}
else
{
break;
}
++cp;
}
return n;
}
where the stuff used inside it is
long index_of (char * pc, char c)
{
/*
Helper function
pc: Pointer to the first character of a character array
c: Character to search
Returns the index of the first instance of
character c in the character array str. If
none is found, returns -1.
*/
char * pfoc = strchr(pc, c); /* Pointer to the first occurrence of character c */
return pfoc ? (pfoc - pc) : -1;
}
and
char digits [] = "0123456789";
If possible, I'd like to cut down on the amount of code by maximizing the use of standard library firepower. I'm fully aware of atoi
, but the problem is that I can't invoke it and recover the number of characters it parsed when it was invoked. Any suggestions?