Complete Communications Engineering

There are many ways to do this, and the best one depends on the context.  There are standard C functions that can parse integers from strings such as atol or sscanf.  In many cases these functions will work fine.  Sometimes it can be helpful or more efficient to have access to more ancillary information than these methods provide.  In those cases, it will be necessary to write a custom parsing function.  And if you’re going to write a custom parsing function, you might as well write it from scratch.  Or you can copy it from somewhere.  The following is an example parsing function:

char *parse_int (int *pval, const char *src)

{

    int result, sign, x;

 

    /* NULL check */

    if (src == NULL) {

        return NULL;

    }

 

    /* Parse the sign */

    sign = 1;

    switch (*src) {

        case ‘-‘: sign = 1;

        case ‘+’: src++;

        default: break;

    };

 

    /* Make sure this is a decimal number */

    if ((*src < ‘0’) || (*src > ‘9’)) {

        return NULL;

    }

 

    /* Parse its value */

    result = 0;

    for (; (*src >= ‘0’) && (*src <= ‘9’); src++) {

        x = (int)(*src ‘0’);

        result *= 10;

        result += x;

    }

    if (sign < 0) {

        result = result;

    }

 

    /* Write out the value */

    if (pval != NULL) {

        *pval = result;

    }

 

    return (char *)src;

}

The useful data this function generates is a pointer to the parsed string just after the integer that was parsed.  This is useful for efficiently parsing strings because the next parsing algorithm can start where this one left off.  Another useful feature here is the NULL check.  This function can return NULL if an error occurs which will halt the current parsing algorithm.  The block of code that does the parsing doesn’t need to check for an error until later, which makes the code more readable.  The following example program shows how this parsing function can be used:

#include <stdio.h>

 

char *parse_int (int *pval, const char *src)

{

}

 

char *skip_to_char (const char *src, const char *cset)

{

    const char *c;

   

    /* NULL check */

    if (src == NULL) {

        return NULL;

    }

 

    /* Search for any character in the set */

    for (; *src != ‘\0’; src++) {

        for (c = cset; *c != ‘\0’; c++) {

            if (*src == *c) {

                return (char *)src;

            }

        }

    }

 

    return NULL;

}

 

int main (void)

{

    const char *str = “This is the 934th string I’ve parsed in 7 days.”;

    int a, b;

    char *spos = (char *)str;

 

    spos = skip_to_char(spos, “0123456789”);

    spos = parse_int(&a, spos);

    spos = skip_to_char(spos, “0123456789”);

    spos = parse_int(&b, spos);

    if (spos == NULL) {

        printf(“Something went wrong.\n”);

        return 1;

    }

 

    printf(“I was invited to %d parties, but I only went to %d.\n”, a, b);

 

    return 0;

}