#include #include "string_conversion.h" #define false 0 #define true 1 /* determine whether the string contains an occurence of either a lowercase or uppercase 'N'. If the string contains such a character then the string might contain the subsequence "nan" which could cause the string conversion functions to mistakenly think the string should be interpreted as "infinity". To prevent this problem, we specifically rule out the string having an 'n' in it. */ int has_an_n(char *str) { return ((strchr(str, 'n') != 0) || ((strchr(str, 'N')) != 0)); } /* convert a string to an integer, returning true for success and false for failure */ int string_to_int(char *str, int *return_value) { char *last_char; // ptr to first char not processed by strtol // first ensure that the first three characters are not some variation // of nan, which represents infinity if ((strlen(str) == 0) || (has_an_n(str))) return false; *return_value = (int)strtol(str, &last_char, 10); // if the end of the string was reached then the string consisted wholely // of numbers, otherwise the string contained trailing characters return (*last_char == '\0'); } /* convert a string to a long, returning true for success and false for failure */ int string_to_long(char *str, long *return_value) { char *last_char; // ptr to first char not processed by strtol // first ensure that the first three characters are not some variation // of nan, which represents infinity if ((strlen(str) == 0) || (has_an_n(str))) return false; *return_value = strtol(str, &last_char, 10); // if the end of the string was reached then the string consisted wholely // of numbers, otherwise the string contained trailing characters return (*last_char == '\0'); } /* convert a string to a float, returning true for success and false for failure */ int string_to_float(char *str, float *return_value) { char *last_char; // ptr to first char not processed by strtod // first ensure that the first three characters are not some variation // of nan, which represents infinity if ((strlen(str) == 0) || (has_an_n(str))) return false; *return_value = (float)strtod(str, &last_char); // if the end of the string was reached then the string consisted wholely // of numbers, otherwise the string contained trailing characters return (*last_char == '\0'); } /* convert a string to a double, returning true for success and false for failure */ int string_to_double(char *str, double *return_value) { char *last_char; // ptr to first char not processed by strtod // first ensure that the first three characters are not some variation // of nan, which represents infinity if ((strlen(str) == 0) || (has_an_n(str))) return false; *return_value = strtod(str, &last_char); // if the end of the string was reached then the string consisted wholely // of numbers, otherwise the string contained trailing characters return (*last_char == '\0'); }