我们如何从scanf()的函数测试返回值? [英] how do we test the return values from the scanf() function?

查看:586
本文介绍了我们如何从scanf()的函数测试返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确认是否从scanf的返回一个值()函数是一个浮动号码或没有。我该怎么办呢?我的code未运行,因为它应该如果错了的数据类型提供给scanf()的函数。同样地,我怎么会确认是否返回的值是一个字符串或没有?

I want to confirm if a value returned from the scanf() function is a floating number or not. How can I do that? My code is not running as it should if wrong data types are supplied to scanf() function. similarly how would I confirm if a value returned is a character string or not?

推荐答案

scanf()的等人返回成功转换次数。

scanf() et al return the number of successful conversions.

如果您有:

scanf("%f", &f);

您应该测试:

if (scanf("%f", &f) == 1)
    ...all OK...
else
    ...EOF or conversion failure...

如果你有几个转换,检查它们全部完成。如果您使用%N '转换',他们是不计算在内。

If you have several conversions, check that they all completed. If you're using %n 'conversions', they aren't counted.

虽然 scanf()的并在EOF返回EOF,你不应该测试对于—您应经常检查,主要是你得到你所期望的转换次数。例如,考虑马车code:

Although scanf() does return EOF on EOF, you should not test for that — you should always check primarily that you got the number of conversions you expected. For example, consider the buggy code:

while (scanf("%f %d %s", &f, &i, s) != EOF)  // Here be BUGS!
    ...loop body...

如果您键入 3.14 X23是,那么你将有一个无限循环,因为 scanf()的将返回1在第一次迭代(它成功地转换3.14),0之后(不是EOF)。

If you type 3.14 x23 yes, then you will have an infinite loop because scanf() will return 1 on the first iteration (it successfully converted 3.14), and 0 thereafter (not EOF).

您可能会确定有:

while ((rc = scanf("%f %d %s", &f, &i, s)) != EOF)
{
    if (rc != 3)
        ...oops data problems...
    else
        ...all OK...
}


从previous的问题来看,你应该考虑使用与fgets()(或可能POSIX 函数getline())读取数据的线,然后用的sscanf()甚至是功能,如与strtol()关于strtod()来从线读取特定值。如果你使用的sscanf(),上述有关检查成功转换的数量仍然适用的意见。


Judging from previous questions, you should be looking at using fgets() (or possibly POSIX getline()) to read lines of data, and then using sscanf() or even functions like strtol() and strtod() to read particular values from the line. If you use sscanf(), the comments made above about checking the number of successful conversions still apply.

我不使用 scanf()的生产code;它仅仅是太艰难了适当控制。我认为这是几乎适合入门程序—不同之处在于它会导致很多困惑。就整体而言,最好的建议是留下清晰的scanf()的的fscanf()。需要注意的是,这并不意味着你必须留下清晰的sscanf(),虽然与 sscanf的甚至需要一些谨慎()

I don't use scanf() in production code; it is just too damn hard to control properly. I regard it as almost suitable for beginning programs — except that it causes lots of confusion. On the whole, the best advice is 'stay clear of scanf() and fscanf()'. Note that that does not mean you have to stay clear of sscanf(), though some caution is needed even with sscanf().

这篇关于我们如何从scanf()的函数测试返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆