Does a string represent a VALID double ?????

Hi guys !
I have a C string, and i need to convert it to a double.
I know i can use function atof()
**** BUT **********
I need to know whether or not the string represents
a VALID double ! (e.g. "8.112" is a valid double
whereas "8.aa2" is not).

Does anybody know how to make sure that the string
is a valid double ??????

Thanx a bunch for any suggestions !

-Kaylie

Comments

  • : Hi guys !
    : I have a C string, and i need to convert it to a double.
    : I know i can use function atof()
    : **** BUT **********
    : I need to know whether or not the string represents
    : a VALID double ! (e.g. "8.112" is a valid double
    : whereas "8.aa2" is not).
    :
    : Does anybody know how to make sure that the string
    : is a valid double ??????
    :
    : Thanx a bunch for any suggestions !
    :
    : -Kaylie
    :

    First of all, atoi will attempt to convert everything to double until it hits an unrecognized letter. So if you have "12.34a8" it will return 12.34.

    If that isn't good enough, say that you only can accept a string where every character is valid, then you can do something like this:

    (Not compiled or tested)

    [code]
    #include
    #include

    typdef enum {FALSE, TRUE} BOOL;

    BOOL isValidDouble (const char* str)
    {

    BOOL isValid = TRUE;
    BOOL foundDot = FALSE;
    int i;

    for(i=0; i<strlen(str); i++)
    {
    if(!foundDot)
    if(str[i]=='.')
    foundDot=1;
    if(!isDigit(str[i]))
    {
    isValid = FALSE;
    break;
    }
    }

    return isValid;
    }
    [/code]

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion