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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

check if input is a valid float number 2

Status
Not open for further replies.

praywin

Programmer
Feb 6, 2003
31
IN
Hi,
I want to check if the input is a valid float number. i.e. it should filter out 12..0 , abc , 12abc etc. I was trying to read in the input as a string but it didn't work that great. Please let me know if you know of some other way.
Cheers,
Pravin.
 
Read the input in a string then convert it with strtod and check if the endptr arg of strtod points to the end of string ('\0' char).

For more info:
Code:
man strtod

Denis
 
Thanks.
I used

num=strtol(input,&endptr,0);
if (endptr!=\'0') {
// number is valid
} else {
//number is invalid
}

but it doesn't work. It gives the same result for any input.
 
Use strtod (for double values) not strtol (for long values).

Do not check if endptr is null but if it points to a null character.

Furthermore, endptr points to the first invalid character, so if endptr points to a null char the number is valid.

Note that if you read from a file, endptr could points to a '\n' character instead of '\0', meaning that your number is followed by an end-of-line.

The following code is an example:
Code:
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
  char input[256];

  while ((void)fprintf(stdout, &quot;Enter a float number :&quot;),
	 fgets(input, sizeof(input), stdin) != (char *)(NULL))
    {
      char   *endptr;
      double value = strtod(input, &endptr);

      if ((endptr[0] == '\0') || (endptr[0] == '\n'))
	(void)fprintf(stdout, &quot;Double number read : %lf\n&quot;, value);
      else
	(void)fprintf(stdout, &quot;garbage characters found: %s\n&quot;, endptr);
    }
  return 0;
}

&quot;When all else has failed, read the manuals.&quot;

Denis
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top