如何限制用户无法在c中输入0

我有以下函数来过滤整数值并重新提示用户。

int checkInput0(void){ int option0,check0; char c; do{ printf("Enter the amount of triangles you want to check: \n"); if(scanf("%d%c",&option0,&c) == 0 || c != '\n'){ while((check0 = getchar()) != 0 && check0 != '\n' && check0 != EOF); printf("[ERR] Invalid number of triangles.\n"); }else{ break; } }while(1); // printf("returning the value of option, which is %f", option); return option0; 

但是,我想将此函数扩展为过滤0。

我似乎错过了一些东西。 非常感谢所有帮助。

提前致谢!

发布的代码没有正确检查’scanf()’返回的值,并且没有完全执行所需的function。

以下提议的代码:

  1. 澄清逻辑
  2. 正确检查I / O错误
  3. 丢弃无效输入
  4. 如果I / O失败,退出程序
  5. 将输入数据与’stdin’清空分开

现在建议的代码:

 do { printf("Enter the amount of triangles you want to check: \n"); if( scanf( "%d", &option0 ) == 1 ) { if( 0 >= option0 ) { // 0 or negative value entered printf("[ERR] Invalid number of triangles.\n"); continue; } // empty stdin while( (check0 = getchar()) != EOF && check0 != '\n' ); // exit while() loop break; } else { // scanf failed perror( "scanf for number of triangles failed" ); exit( EXIT_FAILURE ); } } while(1);