如何检查字符串是否可以转换为一个浮动? [英] How can I check if a string can be converted to a float?
问题描述
首先我上下文是一个编译器的作家谁需要浮点文字(字符串)转换成浮点/双精度值。所以我pretty相信这是一个愚蠢的总新手问题我没有做任何浮动点规划在过去15年。
First my context is that of a compiler writer who needs to convert floating point literals (strings) into float/double values. I haven't done any floating point programming the last 15 years so i'm pretty sure this is a total stupid newbie question.
double res;
errno=0;
*res = strtod((const char*)literal,NULL);
if (errno==ERANGE) throw_a_literal_out_of_range_exception();
return res;
但在C运行时库中没有strtof功能?
but there is no "strtof" function in the c runtime library?
编辑:澄清。我已经知道该字符串'文字'是一个C浮点一个有效的模式。它已经通过一个普通的前pression测试。我只是想检查是否有一个范围/ precision问题。
To clarify. I already know that the string 'literal' is a valid pattern for a C floating point. It already passed a regular expression test. I just want to check if there is a range/precision problem.
究其原因,埃菲尔铁塔源$ C $ C,用户可以写
The reason is in Eiffel source code a user can write
a := {REAL_32} 3.1415
b := {REAL_32} 3.0E200
要投的书面浮点数explit一个32位浮点。我觉得在第二种情况下,编译器应该检测值超出范围,并引发错误或至少是一个警告。
To cast a written floating point number explit to a 32bit floating point. I think in the second case the compiler should detect that the value is out of range and raise an error or at least a warning.
推荐答案
既然你已经在你的价值双击
,你可以检查它是否是的范围之外浮动
:
Since you have your value in a double
, you can just check if it's outside of the range of float
:
#include <stdlib.h>
#include <stdio.h>
#include <float.h>
int main(int argc, char *argv[])
{
double d = FLT_MAX;
if (argc > 1) {
d = strtod(argv[1], NULL);
}
if ((d > 0 && (d > FLT_MAX || d < FLT_MIN))
|| (d < 0 && (d < -FLT_MAX || d > -FLT_MIN)))
printf("Invalid float: %g\n", d);
else
printf("Valid: %g\n", d);
return EXIT_SUCCESS;
}
运行程序:
$ ./a.out
Valid: 3.40282e+38
$ ./a.out 3.5e38
Invalid float: 3.5e+38
$ ./a.out -1e40
Invalid float: -1e+40
您可能会或可能不会需要添加一个测试为正确的关于strtod()
回归,这取决于是否有溢出的可能性双
键入为好。
You may or may not need to add a test for correct strtod()
return, depending upon whether there's a possibility of an overflow in double
type as well.
这篇关于如何检查字符串是否可以转换为一个浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!