From Text to Integer

A program prompts for a value. The user types “12345” at the keyboard, but that input is a string and not the value 12,345. Therefore, the code must convert the string into a value. This task can be accomplished in a number of ways.

The easiest way to make the conversion is to use the scanf() function:

scanf("%d",&value);

The scanf() function, however, won’t understand if the user screws up, potentially creating more work for you to code around that function’s peculiarities.

Another option is to fetch a string and then process it through the strtol() function. That function, defined in stdlib.h, converts a string to a long int variable. It allows for white space before the value, a leading + or - sign, and it can read in hex values prefixed by using 0x or octal values prefixed with a leading 0 (zero).

The strtol() function also terminates reading the string at the first non-digit character. It’s a vast improvement over the atoi() function, which was the C library’s original “ASCII to integer” conversion function. (The atoi() function is also defined in stdlib.h.)

Your challenge this month is to create your own text-to-integer function. I confess that this isn’t an easy exercise. It involves reading a string — a pointer — and using ASCII text conversion tricks to translate characters into values.

To assist you, I’ve created a skeleton below that provides a starting point.

#include <stdio.h>

int convertString(char *string);

int main()
{
    char *value = "24680";
    int result;

    result = convertString(value);
    printf("The string %s represents value %d.\n",
            value,
            result);

    return(0);
}

int convertString(char *string)
{
}

Your tasks is to complete the code by coding the convertString() function. You can get as fancy as you like, although the basic task is to create something that returns an int value from the string argument. Please don’t use strtol() or atoi() or another C library function. That’s cheating. You need to code your own function, which can be done!

As a hint, it helps to know that the ASCII codes for characters ‘0’ through ‘9’ can be converted to values 0 through 9 by subtracting 0x30 (the code for character ‘0’). So, if you were converting single characters, you could do something like:

cvalue = digit - '0';

Where cvalue is an int variable and digit is a single character variable holding characters ‘0’ through ‘9’ inclusive. The result of the above operation would be that cvalue holds the integer value of character variable digit.

I will post my solution in a week.