cvalidating

Need basic help in C with


There is the validating function for my size which i can't manage to code it properly

    void getsize(int* size, int cap){
    while(1){
    printf("Enter the size(whole number) of array from interval (0, %d]: \n", cap);
   if (scanf("%d", size) == 1){
    if ((*size > 1) && (*size <= cap)){
            printf("Size: %d entered\n", *size);
            break;
        } else {
            printf("Invalid size. Try again.\n");
        }
    } else {
        printf("Invalid size. Try again.\n");
        break;
    }
    }
}

What I expect from user is to enter positive whole number. Can anybody fix this or show better solution for this? Thanks.


Solution

  • Your version may accept float numbers since the part before the dot is a valid integer. Instead you can use strtol and check the end of the number is indeed a newline:

    #include <stdio.h>
    #include <stdlib.h>
    void getsize(int* size, int cap){
        char buffer[256], *c;
        while (1) {
            if (fgets(buffer, sizeof(buffer), stdin)) {
                int lsize = strtol(buffer, &c, 10);
                if ((lsize > 1) && (lsize <= cap) && c[0] == '\n'){
                    printf("Size: %d %s entered\n", lsize, c);
                    *size = lsize;
                    return;
                } 
            }
            printf("Invalid size. Try again.\n");
        }
    }
    
    int main ( ) {  
        int size;
        getsize(&size, 10);
        return 0;
    }