本文介绍了用scanf函数输入验证()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有从用户接受的整数,在加法运算中使用该号码的程序。

I have a program which accepts an integer from the user and uses this number in an addition operation.

在code,我现在用接受数字是这样的:

The code which I am using to accept the number is this:

scanf("%d", &num);

我如何验证输入,这样如果用户输入字母或小数点的数字,显示在屏幕上的错误信息?

How can I validate the input such that if the user enters a letter or a number with the decimal point, an error message is displayed on the screen?

推荐答案

您应该使用 scanf函数返回值。从:

You should use scanf return value. From man scanf:

这些函数返回成功匹配和分配的输入项,其可以是少于规定的,或者甚至零在早期匹配失败的情况下的数量。

因此​​,它可能是这样的:

So it may look like this:

if (scanf("%d", &num) != 1)
{
    /* Display error message. */
}

注意它不为数字小数点工作。为此你应该相当使用解析和与strtol 为例。这可能是比较复杂的。

Notice it doesn't work for "numbers with the decimal point". For this you should rather use parsing and strtol for instance. It may be a bit more complex.

这篇关于用scanf函数输入验证()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 16:22
查看更多