Search code examples
ccharscanfexit-code

How to get errors to print if chars are entered using scanf in C


I'm experimenting with c at the moment and this program is suppose to get the user to input a number between ranges 10-100 if he enters anything that doesn't meet these conditions, the program will exit with an error code 1. anything that meets conditions, program will exit with 0. Down below is the code so far, but refuses to print correct error on char detection.

#include <stdio.h>
#include <stdlib.h>


int intGet(int ,int);
int error();
int userIn;
char x;

int main(void) {
    printf("Enter a number in between [10 -­100]: \n");
    x = scanf("%d", &userIn);
    intGet(x, userIn);

    return EXIT_SUCCESS;
}

int intGet(int min,int max ) {
    min = 10;
    max = 100;

    x = userIn;
    if ((x < min) || (x > max)) {
        printf("Input out of Range\n");
        exit(EXIT_FAILURE);
    } else if (x == 0) {
        printf("Incorrect input format\n");
        exit(EXIT_FAILURE);
    } else {
        printf("Read %d\n", userIn);
        exit(EXIT_SUCCESS);
    }
}

int error() {

}

Solution

  • It is not clear what your problem is. What error do you expect?

    You need to tidy up your code. There are few things. scanf returns int value - the number of input items assigned. You assign the return value to char x. Then you assign the input value to x. What is the logic behind? What do you expect? I guess your problem is logical. I suggest you:

    1. Handle the return and the input values separately
    2. Remove exit() statement, use return value instead. exit() terminates the program.
    3. Remove globals
    4. If the above doesn't help use printf to see what is being processed

    Example:

    int main(void) {
        printf("Enter a number in between [10 -­100]:\n");
        int userIn;
        int x = scanf("%d", &userIn);
    
        // for debug
        printf("Scanned: %d, returned: %d", x, userIn);
    
        int result = intGet(x, userIn);
        // analyse the result here
        switch (result) {
            case RES_SUCCESS:
               return SUCCESS;
            case ...
        }
    }
    
    
    int intGet(int x, int value) {
        int const min = 10;
        int const max = 100;
    
        if (x != 1) {
            return RES_ERROR_NO_INPUT;
        }
    
        if (value < min || value > max) {
            return RES_ERROR_OUT_OF_RANGE;
        }
    
        return RES_SUCCESS;
    }