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

问题描述

我有一点限制了用户输入的问题。我只想要整数1,2或3是输入。 DO .. while循环确实为无效的整数投入的工作,但我怎么不顾字符串/字符输入?我还需要反复询问用户是否曾经输入无效。

I'm having a bit of a problem restricting the user input. I only want the integers 1,2 or 3 to be the input. Do.. while loop does the job for invalid integer inputs, but how do I disregard string/character inputs? I also need to ask the user repetitively if ever the input is invalid.

更新:

int problem;

printf("Please select the problem that you want to solve:\n");
printf("\t 1-Problem 1\n");
printf("\t 2-Problem 2\n");
printf("\t 3-Problem 3\n");
while( scanf("%d", &problem)==0 && (problem!=1 || problem !=3 || problem !=2))
{int c;
while((c=getchar())!='\n' && c!=EOF);
printf("Please select the problem that you want to solve:\n");
printf("\t 1-Problem 1\n");
printf("\t 2-Problem 2\n");
printf("\t 3-Problem 3\n");
}

这看起来有点由于多用printfs的凌乱。我只是不想冗长codeS一行。无论如何,我想只有1,2或3为输入。如果输入的输入是无效的,该程序再次询问用户,直到用户输入了有效输入

It kinda looks messy because of the multiple printfs. I just don't want lengthy codes in one row. Anyway, I wanted only 1,2, or 3 as inputs. If the entered input is invalid, the program asks the user again until the user inputs a valid input.

的code工作的无效输入,例如单词,字母,字符,等等。然而,如果用户输入1.2,将其与1进入这不应该是这样的。 0也不接受。我可以做我的code什么限制呢?

The code works for invalid inputs such as words, letters, characters, etc. However, if the user inputs 1.2 , it proceeds with 1 which should not be the case. 0 isn't accepted either. What can I do to my code to restrict them?

推荐答案

scanf函数%d个将失败和在无效的输入的情况下返回0(如字符(S))。所以,只检查是否未能通过检查它的返回值 scanf函数

scanf with a %d will fail and return 0 in case of invalid inputs(like character(s)). So, just check if the scanf failed by checking the return value of it.

while(scanf("%d",&num)==0 && (num<=1 || num >=3)) //Invalid input if this is true
{
  int c;
  while((c=getchar())!='\n' && c!=EOF); //Clear the stdin

  printf("Invalid input. Try again\n");
}

while((c=getchar())!='\n' && c!=EOF);

清除标准输入流,使 scanf函数不一遍又一遍读无效的输入产生一个无限循环。

clears the standard input stream so that scanf does not read the invalid input again and again resulting in an infinite loop.

注意 scanf函数可以的回报 EOF 。这将导致程序认为用户输入有效输入。您可以添加一个检查,看是否从 scanf函数的返回值不是 EOF 。此外,你应该初始化 NUM 为一个数字,是不是1,2或3,避免调用未定义的行为。

Note that scanf can return EOF. This will cause the program to think that the user has entered valid input. You can add a check to see if the return value from scanf isn't EOF. Also, you should initialize num to a number that is not 1,2 or 3 to avoid invoking Undefined Behavior.

这篇关于输入限制用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:01