0

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.

shanet
  • 7,246
  • 3
  • 34
  • 46
user3529236
  • 107
  • 2
  • 9

2 Answers2

0

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;
}
perreal
  • 94,503
  • 21
  • 155
  • 181
  • `atoi` isn't a function I would recommend, as you can't differentiate between an invalid number in the string and zero. Instead I'd recommend [`strtol`](http://en.cppreference.com/w/c/string/byte/strtol). Though I admit that in this case it really doesn't matter as zero is invalid in any case. – Some programmer dude Apr 13 '14 at 18:05
0

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;
}
}
}
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34