在C中validation输入

我想编写一个程序,以便读取两个POSITIVE INTEGER作为输入,并拒绝用户输入除两个正整数以外的任何东西。我试图使用下面的代码,但它不起作用。

编辑1:删除了第一个scanf。 编辑2:添加了检查负值的代码。

代码不起作用:

#include  #include  int main () { unsigned int no1,no2,temp; char check; printf("Enter two positive integers.\n"); scanf("%i %i %c", &no1, &no2 ,&check); if(scanf("%i %i %c", &no1, &no2,&check) != 3 || check != '\n'){ printf("Invalid input!!.\n"); exit(EXIT_FAILURE); } else if (no1 <= 0 || no2 <= 0) { printf("Invalid input!!.\n"); exit(EXIT_FAILURE); } int copy1,copy2; copy1 = no1; copy2 = no2; while(no2 != 0) { temp = no1 % no2 ; no1 = no2; no2 = temp ; } printf("The HCF of %i and %i is %i. \n",copy1,copy2,no1); return 0; } 

工作代码:

 #include  #include  int main () { int no1,no2,temp; printf("Enter two positive integers.\n"); int numArgs = scanf("%i%i", &no1, &no2 ); if( numArgs != 2|| no1 <= 0 || no2 <= 0 ){ printf("Invalid input!!.\n"); exit(EXIT_FAILURE); } int copy1,copy2; copy1 = no1; copy2 = no2; while(no2 != 0) { temp = no1 % no2 ; no1 = no2; no2 = temp ; } printf("The HCF of %i and %i is %i. \n",copy1,copy2,no1); return 0; } 

它继续,直到我连续输入5个整数或2个字符而不是\ n。 它永远不会计算HCF但是如果我删除“if”块它会起作用。

编辑3:现在我不想阅读换行符。

检查负值的第二个if块也不起作用。

  scanf("%i %i %c", &no1, &no2 ,&check); if(scanf("%i %i %c", &no1, &no2 ,&check ) != 3 || check != '\n' ) 

问题出在这里。 你正在调用scanf()两次,这意味着它要检查两次输入。 如果要检查输入的数量,只需在第一次从用户处获取时保存scanf的返回值; 此外,无符号整数应使用%u“扫描”,而不是%i。 在这里阅读更多关于scanf()的信息 。

另外,我认为scanf实际上并没有考虑到换行符。 但是,用户必须按Enter键才能向您提交输入,因此您无需进行检查。

  int numArgs = scanf("%u %u", &no1, &no2); if(numArgs != 2){ .... 

但是,如果您因某种原因想要检查换行符,请尝试以下操作:

 int numArgs = scanf("%u %u%c", &no1, &no2, &check); if(numArgs != 3 || check != '\n'){ .... 

您在代码中有两个问题,如问题中所示(编辑前):

  1. 您为相同的变量调用scanf 两次 ,强制用户输入两次相同的数据。

  2. 使用的格式不会读取换行符,因此表达式check != '\n'将始终为true。

对于数字1,只需删除第一个scanf调用。 对于数字2,用户必须始终按Enter键才能结束输入,因此无需检查。 如果你真的想确定,那么使用例如fgets读取其中包含数字的行,并使用sscanf来解析值。