Search code examples
cscanf

Input validation recursive function (want positive integer) fails to work when negative integer is input


int get_num_order(){
    char term;
    int input;
    printf("Please enter the number of items you want to order: ");
    if(scanf(" %d%c", &input, &term) != 2 || term != '\n' || input < 0){
        // printf("%d", input);
        scanf("%*[^\n]");
        get_num_order();
    }
    else{
        // printf("%d", input);
        return input;
    }
    
}

I've been following various tutorials on the internet, and this one worked the best so far. It successfully handles decimals, letters, and whitespace, but it gets stuck at negative numbers. The program just pauses. I'm not sure what the issue is, help?


Solution

  • scanf("%*[^\n]"); was blocking the function after entering a negative number. If the first scanf read the negative number and a newline, there was nothing in the buffer to remove.
    This seems to work.

    int get_num_order(){
        char term = 0;
        int input = 0;
        printf("Please enter the number of items you want to order: ");
        if(scanf("%d%c", &input, &term) != 2 || term != '\n' || input < 0){
            // printf("\t%d\n", input);
            if ( term != '\n') {
                scanf("%*[^\n]"); // remove all from buffer to newline
            }
            input = get_num_order();
        }
        return input;
    }