C中的输入限制

我在限制用户输入方面遇到了一些问题。 我只想要整数1,2或3作为输入。 Do .. while循环完成无效整数输入的工作,但是如何忽略字符串/字符输入? 如果输入无效,我还需要重复询问用户。

更新:

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,它看起来很乱。 我只是不想在一行中使用冗长的代码。 无论如何,我只想要1,2或3作为输入。 如果输入的输入无效,程序将再次询问用户,直到用户输入有效输入。

该代码适用于无效输入,如单词,字母,字符等。但是,如果用户输入1.2,则进行1,但不应该是这种情况。 也不接受0。 我可以对我的代码做些什么来限制它们?

带有%d scanf将失败,并且在输入无效(如字符)的情况下返回0。 因此,只需通过检查scanf的返回值来检查scanf失败。

 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不会再次读取无效输入,从而导致无限循环。

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