Question

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.

Was it helpful?

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;
}

OTHER TIPS

I can't see any use of receiving size as a parameter to getsize since u only need the limits which can be provided by "cap" itself.Secondly,an address to a variable is to be provided to scanf.

void getsize(int cap){
   int size;
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;
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top