Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is double numeric?

Status
Not open for further replies.

DerPflug

Programmer
Mar 28, 2002
153
US
I am very new to C so this may seem a silly question.

I've got a simple application where I have the user enter a unit price for an inventory part. I need to validate that the user has entered a numeric answer before I let them save it to a binary file. I've got the variable defined as a double. It looks something like this:

double price;

printf("Enter unit price for the part: ");
scanf("%lf", &price);

I need to flag the user if they've entered something like
34m.50 or any other non numeric character.

Any help would be greatly appreciated.
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int isDouble( char* value )
{
char cTemp;
int i,oneDec;

oneDec=0;
cTemp =0;
i =0;

while( 1 )
{
cTemp=value[i++];
if( cTemp=='\0' )
break;

if( cTemp=='.' && ( !oneDec ) )
{
oneDec=1;
continue;
}

if( !isdigit( cTemp ) )
return 0;
}

return 1;
}


int main( void )
{
char holdDouble[1024];
double dPrice;

printf( &quot;Enter price:&quot; );
fgets( holdDouble,1024,stdin );
*( strrchr( holdDouble,'\n' ) )='\0';

if( isDouble( holdDouble ) )
{
dPrice=atof( holdDouble );
printf( &quot;Your price is $%0.2lf\n&quot;, dPrice );
}
else
printf( &quot;Invalid double\n&quot; );

return 0;
} Mike L.G.
mlg400@blazemail.com
 
Just to expand on the code that liquidBinary has supplied. The best way to test for this type of validation is to read the whole thing as a string, in this case using fgets. Then break it down and perform the necessary checks on each character. If it passes the validation it is then safe to convert, in this case using the atof function. You will avoid serious errors if you do it this way.
 
I had opted for reading it as a string but thought this might be going around the long way. Thanks for clarifying that for me.
 
Read in as string and use strtod() to test/convert the charactes.

The secound argument of strtod() is a pointer that when the fucntion returns, points to the position of the input where the conversion end. If input is a valid numeric format, the second argument points to the terminating '\0'. Otherwise, it points to an invalid character.

Code:
    char *pValue;
    // string data pointed by pValue
    char *pEndPtr;

    double dValue = strtod(pValue, &pEndPtr);
    if (*pEndPtr != '\0')
    {
        // Not a valid double format...
    }

Hope this helps

Shyan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top