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

时间:2017-10-31 12:49:05

标签: c

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

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。

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

提前致谢!

1 个答案:

答案 0 :(得分:1)

发布的代码未正确检查'scanf()'返回的值,并且不能完全执行所需的功能。

以下提议的代码:

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

    现在建议的代码:

    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);
    
相关问题