如何防止用户在c中输入0或负数

时间:2017-11-01 10:49:49

标签: c

我写过这个函数:

float checkInput1(void){
    float option1,check1;
    char c;

    do{
        printf("Enter the first side of the triangle: ");

        if(scanf("%f%c",&option1,&c) == 0 || c != '\n'){
            while((check1 = getchar()) != 0 && check1 != '\n' && check1 != EOF);
            printf("\t[ERR] Invalid number for the triplet.\n");
        }else{
            break;
        }
    }while(1);
    return option1;
}

要阻止用户输入字母等,我想扩展此验证功能,以便用户无法输入0或负数。 我怎么做? 提前致谢

1 个答案:

答案 0 :(得分:0)

考虑使用fgets进行输入并使用strtod进行解析。除非有理由,否则请使用double代替float。使用min -HUGE_VALF和max HUGE_VALF会将double限制为float的范围。这使用min 1.0e-10来拒绝零和更小。有效分隔符为"\n",但可以根据需要进行更改以允许使用逗号或其他分隔符。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <math.h>

int parse_double ( char *line, char **next, char *delim, double *value, double min, double max) {
    char *end = NULL;
    double input = 0.0;

    errno = 0;
    input = strtod ( line, &end);
    if ( ( errno == ERANGE && ( input == HUGE_VAL || input == -HUGE_VAL))
    || ( errno != 0 && input == 0.0)){
        perror ( "input: ");
        return 0;// failure
    }
    if ( end == line) {
        line[strcspn ( line, "\n")] = '\0';
        printf ( "input [%s] MUST be a number\n", line);
        return 0;// failure
    }
    if ( *end != '\0' && !( delim && ( strchr ( delim, *end)))) {// is *end '\0' or is *end in delim
        line[strcspn ( line, "\n")] = '\0';//remove trailing newline
        printf ( "problem with input: [%s] \n", line);
        return 0;// failure
    }
    if ( next != NULL) {// if next is NULL, caller did not want pointer to end of parsed value
        *next = end;// *next allows modification to caller's pointer
    }
    if ( input < min || input > max) {
        printf ( "out of range\n");
        return 0;// failure
    }
    if ( value != NULL) {// make sure value is not NULL
        *value = input;// *value allows modification to callers double
    }
    return 1;// success
}

int read_double ( double *dValue) {
    char line[900] = {'\0'};
    int valid = 0;

    *dValue = 0.0;
    do {
        printf ( "Enter a number or quit\n");
        if ( fgets ( line, sizeof ( line), stdin)) {//read a line
            if ( strcmp ( line, "quit\n") == 0) {
                return 0;//exit when quit is entered
            }
            valid = parse_double ( line, NULL, "\n", dValue, 1.0e-10, HUGE_VALF);
        }
        else {
            return 0;//fgets failed
        }
    } while ( !valid);

    return 1;
}

int main()
{
    double dResult = 0.0;

    if ( read_double ( &dResult)) {
        printf ( "You entered %f\n", dResult);
    }

    return 0;
}