c - 如何使用c中的库函数验证包含十六进制浮点常量的字符串

标签 c string

例子:

  1. 0x11.00 -> 有效

  2. 0X1.000 -> 有效

  3. 0x11.1L -> 有效

最佳答案

您可以使用 strtod :

链接页面对其进行了详细描述,但这是我刚刚编写的示例代码:

#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;
}

输出:

   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

关于c - 如何使用c中的库函数验证包含十六进制浮点常量的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6467788/

相关文章:

c - 如何限制fifo的用户数量?

C - getopt 切换 while 循环和无效选项的默认情况

c - 将结构添加到数组

javascript - 在 JavaScript 中过滤数字和括号最有效的方法是什么?

ios - 如何将文本字符串转换为十六进制字符串?

c - 如何将数组传递给无法修改它的函数?

c - 段错误,尽管代码从未执行?

python - 在 Python turtle 事件处理程序中比较坐标时出现 TypeError

javascript - JavaScript 字符串如何是一组 "elements"16 位无符号整数值?

python - 从大字符串中拆分时间的出现