检查输入其他浮动止损 [英] Check if input is float else stop
问题描述
scanf("%f", &num);
我要检查如果那是一个有效的浮点型变量和停止执行,如果有像符号@
或!
或%
等
建议?
推荐答案
scanf函数
不是你的朋友,在这里。即使你检查结果
确保你成功地读取一整说法,一点不
真正保证输入的是一个真正意义上有效的。
scanf
is not your friend, here. Even if you check the result to
ensure that you read one whole argument successfully, that doesn't
really guarantee that the input is valid in a meaningful sense.
就像给定输入:
1!!!1!oneone!
在看完后的第一个
解析将停止(但成功) 1
%F
并留下读指针在以下!
。这可能不是什么
你认为有效的输入。
the %f
parsing will stop (but succeed) after reading the first 1
,
and leave the read pointer at the following !
. This may not be what
you consider "valid input".
在这种情况下,尝试:
if (scanf("%f%c", &f, &c) == 2 && isspace(c))
/* success */
这将,但是,接受这样的话:
This will, however, accept things like:
1 oneoneonespace!bang
如果在同一行上的任何被认为垃圾,然后它获取
困难的,因为 scanf函数
没有空间区分和
换行。也许尝试是这样的:
If anything on the same line is to be considered garbage, then it gets
difficult, because scanf
doesn't distinguish between spaces and
newlines. Perhaps try something like this:
char buffer[1024];
if (fgets(buffer, sizeof(buffer), stdin) != NULL)
{
if (sscanf(buffer, "%f %c", &f, &c) == 1)
/* success */
}
这篇关于检查输入其他浮动止损的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!