0

I have a program that accepts two command line inputs

e.g.

./myprog 12,4,35,12,65 4

I want to check if argv[1] is a array of comma separated integers.

This is what I tried so far:

int isNumber(char *argv) {
    int counter;
    long val;
    char *next;
    int size_of_array = sizeof argv / sizeof * argv;
    
    printf("start");

    for (counter = 0; counter <= size_of_array; counter++) {
        printf("start 2");
        val = strtol (argv[counter], &next, 10);

        if ((next == argv[counter]) || (*next != '\0')) {
            printf ("'%s' is not valid\n", argv[counter]);
            int num_check = 0;
            return num_check;
        } else {
            printf ("'%s' gives %ld\n", argv[counter], val);
            int num_check = 1;
            return num_check;
        }
    }
}

int main(int argc, char * argv[]) {
    char *myarg = NULL;
    myarg = argv[1];
    int num_check = isNumber(myarg);

    return 0;
}

How can I achieve this?

Pierre François
  • 5,850
  • 1
  • 17
  • 38
  • You should not access elements of 'argv' without checking 'argc' first to know if there even are arguments. The way you calculate 'size_of_array' is wrong. You are dividing the size of a char pointer by the size of a char. Since 'argv' (in 'isNumber') is a string, you can use 'strlen' to get the string length. – lulle2007200 May 06 '21 at 09:02
  • Also you are passing a 'char' to 'strtol'. It expects a 'char' pointer. – lulle2007200 May 06 '21 at 09:06
  • By the way, if you just want to check if the first argument is composed of numbers and commas, you can just use a simple for loop along the length of the first argument to check every character to be between `'0'` and `'9'` or equal to `','`. – Ganathor May 06 '21 at 10:21

0 Answers0