Input only number C programming

前端 未结 2 1782
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 12:02

currently i am doing a program to get the input (0 to 50) from the user. If the number is out of the range then the number will not be counted. After that, i will calculate and

相关标签:
2条回答
  • 2021-01-29 12:42

    like this

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <limits.h>
    
    int get_int(const char *prompt){
        char buff[32];
    
        for(;;){
            fputs(prompt, stdout);fflush(stdout);
            if(fgets(buff, sizeof buff, stdin)){
                if(strchr(buff, '\n')){
                    char *endp;
                    long n;
    
                    errno = 0;
                    n = strtol(buff, &endp, 10);
                    if(errno == 0 && *endp == '\n' && INT_MIN <= n && n <= INT_MAX)
                        return n;
                } else {//too long input
                    while(getchar() != '\n');
                }
            } else {//input EOF
                continue;//ignore EOF
            }
        }
    }
    
    int main(void){
        int n = 0, score, min = INT_MAX, max = INT_MIN;
        double total = 0, average;
    
        printf("Enter test scores,-1 to exit\n");
        while((score = get_int("* Scores[%d] (0-50) : ")) != -1){
            if(score < 0 || score > 50)
                continue;
    
            total += score;
            if(score > max)
                max = score;
            if(score < min)
                min = score;
            ++n;
        }
        if(n){
            average = total / n;
            printf("Average marks = %.2f\n", average);
            printf("MIN:%d\n", min);
            printf("MAX:%d\n", max);
        } else {
            puts("No valid input");
        }
    }
    
    0 讨论(0)
  • 2021-01-29 12:43

    You could choose among options:
    A. Take input as string and then verify if the string is number. Else, discard it.
    B. Trap key downs. If if is alphabet or symbol, discard. If 0-9, use it.

    0 讨论(0)
提交回复
热议问题