用scanf函数输入验证() [英] Input validation using scanf()

查看:122
本文介绍了用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函数返回值。从 男人scanf函数

You should use scanf return value. From man scanf:

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

Return Value

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

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

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函数输入验证()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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