如何限制用户仅输入整数并拒绝scanf中的任何其他字符? [英] How to restrict the user to only input whole number and refuse any other characters in scanf?

查看:59
本文介绍了如何限制用户仅输入整数并拒绝scanf中的任何其他字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取用户输入,并允许他们仅输入一个也是正数的整数.

我正在尝试解决此任务

  printf(输入整数中的第一个和第二个数字:");scanf(%d,%d",& first,& second);if(input!='\ n')//注意这一行,我正在尝试检查是否是一个字符//printf(错误!字符不被接受!\ n");否则,如果(First< = 0)printf(错误!首先必须是一个正值!\ n");否则(第二个< = 0)printf(错误秒必须为正值!\ n"); 

上面的代码将检查两件事.一,如果用户输入了我想要的字符.其次,如果数字为正.

我如何实现这些检查?

解决方案

您不能限制用户输入的字符.您应该阅读用户给出的所有内容,并决定如何处理.

如果要使用scanf,则可能是这样的:

  int ret = scanf(%d",& num); 

scanf 的返回值显示成功读取的的数量.例如:

  12<-此输入返回1,num将为12asd<-此输入返回0,num将保持不变123xf<-此输入返回1,num将为123 

在最后一个示例中, xf 将保留在输入中,而另外 scanf s将读取它.

因此对于第一个 if ,您只需检查 scanf 的返回值是否为1.否则,您将无法从输入中读取数字./p>

对于第二个 if ,检查 num< = 0

I'm trying to get user input and allowing them to only input a whole number which is also positive.

I'm trying to figure out this task

printf("Enter the first and second number in whole number: ");
scanf("%d,%d", &first, &second);

if (input != '\n') //notice this line I'm trying to check if is a character//
    printf("Error! CHARACTER NOT ACCEPTED!!\n");

else if (First <= 0)
    printf("Error! First must be a positive value!\n");

else if (Second <= 0)
    printf("Error Second must be a positive value!\n");

The code above will check for two things. One, if the user has input the characters I want. Second, if the number is positive.

How do I realize these checks?

解决方案

You cannot restrict the characters the user inputs. You should read whatever the user gives you and decide what to do with it.

If you want to use scanf, it could be like this:

int ret = scanf("%d", &num);

scanf's return value shows the number of %s it successfully read. For example:

12      <-- this input returns 1, num will be 12
asd     <-- this input returns 0, num will be untouched
123xf   <-- this input returns 1, num will be 123

In the last example, xf will stay in input and further scanfs would read it.

So for the first if, you simply check if the return value of scanf is 1. If not, then you couldn't read a number from input.

For the second if, check if num <= 0

这篇关于如何限制用户仅输入整数并拒绝scanf中的任何其他字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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