From Text to Integer – Solution

This month’s Exercise is to code a function that converts a string of text numbers into an integer value. If you used the skeleton provided, then your program’s output would look like this:

The string 24680 represents value 24680.


Click here to view/download my solution.

Here’s what I did in the convertString() function, which starts at Line 18 in my example:

int convertString(char *string)
{
    char *s;
    int total,byten;

I added a second pointer, s, because I don’t want to lose track of the base address held in string. The total variable holds the calculated integer total, what programmers would call an accumulator. byten is the power-of-tens operator, which I’ll explain in a bit.

The next chunk of code (at Line 23) initializes the variables:

/* initialize variables */
    s = string;
    total = 0;
    byten = 1;

Numbers are read left-to-right, but by going right-to-left you get the smaller values first. So to convert the string, the code starts the conversion with the smallest value. The next part of the code locates that terminus:

/* find the last character in the string */
    while(*s)
    {
        s++;
    }
    s--;

Pointer s hunts down the last character in the string. That character is the '\0' null character, which reads as FALSE and thus terminates the while loop.

The s-- operation (Line 33) backs up the pointer to reference that character before the '\0', which is the one’s digit in the string.

If you were writing a text-to-int function, then you’d want to do more character testing as you backup through the string. Ensure that each character is a digit and, if not, terminate the loop at the first non-digit.

The workhorse loop in the function starts at Line 36:

/* Do the math */
    while(s >= string)
    {
        total += (*s - '0') * byten;
        byten *= 10;
        s--;
    }

The while loop backs up through the digits, which is why the condition is s >= string. The s pointer is decremented (in the code at Line 40), which is how the loop moves.

The total calculation (Line 38) takes the ASCII value of character *s and multiplies it by the value of the byten variable. For the first (far right) character in the number, the byten variable is 1 — the one’s position.

The value of byten is then multiplied by 10 for the 10’s place, then 100’s, 1000’s and so on.

As this loop repeats, the values are accumulated in the total variable. When the while loop is done, meaning that no more characters are left to read, the value total is returned from the function.

Yes! This was a tough assignment! Kudos if you managed it on your own.