开发者

How to validate string containing hexadecimal floating constant by using library functions in c

Example:

  1. 0x11.00 -> valid

  2. 开发者_如何学编程0X1.000 -> valid

  3. 0x11.1L -> Valid


You can use strtod:

The linked page describes it in detail, but here is an example code I just wrote:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <math.h>
#include <float.h>

/* Test if data represents a double.  Returns 1 on success, 0 on failure.
   Print the double value for debugging. */
static int validate_and_print(const char *data)
{
    char *eptr;
    double d;
    errno = 0;
    d = strtod(data, &eptr);
    if (d == 0 && eptr == data) {
        fprintf(stderr, "%10s is not a valid double\n", data);
        return 0;
    }
    /* strtod converted the string to a number, but there are extra characters.
       You can check 'eptr' here for what they are, and take further action
       if needed */
    if (*eptr) {
        fprintf(stderr, "%10s has extra characters\n", data);
        printf("%10s = %g\n", data, d);
        return 1;
    }
    if ((d == HUGE_VAL || d == -HUGE_VAL) && errno == ERANGE) {
        fprintf(stderr, "%10s outside of range\n", data);
        return 0;
    }
    if (errno == ERANGE) {
        fprintf(stderr, "%10s may have caused an underflow\n", data);
        printf("%10s = %g\n", data, d);
        return 1;
    }
    printf("%10s = %g\n", data, d);
    return 1;
}

int main(void)
{
    char *data[] = { "0x11.00", "0X1.000", "0x11.1L", "1.0e-400", "test" };
    size_t N = sizeof data / sizeof *data;
    size_t i;

    for (i=0; i < N; ++i)
        validate_and_print(data[i]);
    return 0;
}

Output:

   0x11.00 = 17
   0X1.000 = 1
   0x11.1L has extra characters
   0x11.1L = 17.0625
  1.0e-400 may have caused an underflow
  1.0e-400 = 0
      test is not a valid double
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜