terribleProgrammer terribleProgrammer - 2 months ago 6
C Question

Check if string from main is a valid float

I currently have the below code. However if something like 3.1?43 is entered it is still labeled as a float. I know that I am not properly checking after the . but I am unsure of how to check for that.

int floatNum(char *s) {
char *ptr = s;
char *ep = NULL;
long i = strtol(s, &ep, 0);

//check if converted to long int
if (!*ep) {
return false;
}

//Check if char
if (*ep == 'e' || *ep == 'E' || *ep == '.') {
return true;
}

return false;
}

Answer

To test if a string is a valid floating point value, use strtod. This function parses numeric strings with an optional decimal point and an optional exponent specifier ("e" or "E"):

char *p;

errno = 0;
double f = strtod(str,&p);
if (errno) {
    printf("conversion failed");
}
if (strlen(str)==0) {
    printf("empty string\n");
} else {
    printf("f=%f\n", f);
    if (*p == 0) {
        printf("entire string valid\n");
    } else {
        printf("extra characters: %s\n", p);
    }
}