问题描述
在我的大学里,我被要求编写一个程序来查找两个输入的总和,因此我应该首先检查输入是否有效.
I was asked to write a program to find sum of two inputs in my college so I should first check whether the input is valid.
例如,如果我输入2534.11s35
,则该程序应检测到由于该输入中的s
,所以它不是此程序的有效输入.
For example, if I input 2534.11s35
the program should detect that it is not a valid input for this program because of s
in the input.
推荐答案
1)将输入作为字符串char buf[Big_Enough]
.我希望160位数字可以处理除最不可思议的浮动"字符串之外的所有字符串.
1) Take input as a string char buf[Big_Enough]
. I'd expect 160 digits will handle all but the most arcane "float" strings.
#define N 160
char buf[N];
if (fgets, buf, sizeof buf, stdin) {
2)将float strtof()
应用于float
,(strtod()
表示double
,strtold()
表示long double
).
2) Apply float strtof()
for float
, (strtod()
for double
, strtold()
for long double
).
char *endptr;
errno = 0;
float d = strtof(buf, &endptr);
// endptr now points to the end of the conversion, if any.
3)检查结果.
if (buf == endptr) return "No_Conversion";
// Recommend to tolerate trailing white-space.
// as leading white-spaces are already allowed by `strtof()`
while (isspace((unsigned char)*endptr) {
endptr++;
}
if (*endptr) return "TrailingJunkFound";
return "Success";
4)如果需要,进行极端测试.
4) Tests for extremes, if desired.
此时,输入为数字.问题仍然存在,即有限字符串"是否可以用有限的float
表示:如果| result |在0
或[FLT_TRUE_MIN...FLT_MAX]
的范围内.
At this point, the input is numeric. The question remains if the "finite string" an be well represented by a finite float
: if a the |result| is in range of 0
or [FLT_TRUE_MIN...FLT_MAX]
.
这涉及到查看errno
.
转换成功",但float
范围之外的有限字符串值变为HUGE_VALF
,可能是无穷大或FLT_MAX
.
The conversion "succeed" yet finite string values outside the float
range become HUGE_VALF
which may be infinity or FLT_MAX
.
Wee |值|接近0.0,但不等于0.0成为[0.0 ... INT_MIN]
范围内的值.
Wee |values| close to 0.0, but not 0.0 become something in the range [0.0 ... INT_MIN]
.
由于目标是检测转换是否成功(确实如此),所以我将这些细节留给一个问题,以期深入了解 value 的含义.
Since the goal is to detect is a conversion succeeded (it did), I'll leave these details for a question that wants to get into the gory bits of what value.
一种替代方法是使用fscanf()
直接读取和转换,但是那里的错误处理也有麻烦,并且难以移植控制.
An alternative is to use fscanf()
to directly read and convert, yet the error handling there has its troubles too and hard to portably control.
典型的float
范围是+/- 10 .因此,允许40个左右的字符是有意义的.精确打印FLT_TRUE_MIN
的 可能需要150个字符.要将任意浮动"字符串与FLT_TRUE_MIN
字符串与下一个较大的字符串区分开,需要大约几个数字.
Typical float
range is +/- 10. So allowing for 40 or so characters makes sense. An exact print of FLT_TRUE_MIN
can take ~150 characters. To distinguish a arbitrarily "float" string from FLT_TRUE_MIN
from the next larger one needs about that many digits.
如果浮动"字符串不是任意的,而是仅来自打印出的float
的输出,那么就需要很少的数字-大约40.
If "float" strings are not arbitrary, but only come from the output of a printed float
, then far few digits are needed - about 40.
当然,允许额外的前导/尾随空格和零是明智的选择.
Of course it is wise to allow for extra leading/trailing spaces and zeros.
这篇关于如何检查输入是否为数字(浮点型)或某些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!