MrHardzys
MrHardzys

Reputation: 11

Check if a command line argument is an integer

I have to check if given argument is integer or not. I can't use [] and memory allocation, i tried using isdigit(); but its not working for me. Thanks for any advices and help.

int main(int argc, char *argv[]) {

    int sum=0, i;

    if(argc<2)
    {
        printf("Not enough arguments");
        return 9;
    }
    for (i=1; i<argc; i++)
    {
        if (!isdigit(atoi(*(argv+i))))
        {
            printf("Incorrect input");
            return 1;
        }
    }   
    for(i=1; i<argc; i++)
    {
        sum+=atoi(*(argv+i));
    }

    printf("%d", sum);

    return 0;
}

It should show "Incorrect input" and return 1 if one of numbers aren't integer, but when i'm using isdigit everytime programs prints "Incorrect input" even when all numbers are integers.

Upvotes: 0

Views: 1110

Answers (1)

chux
chux

Reputation: 153338

to check if given argument is integer or not.

Use strto*() family of functions. @Some programmer dude

Example: Test if int?

bool is_int(const char *arg) {
  char *endptr;
  errno = 0;
  long value = strtol(arg, &endptr, 10);

  // Various tests, adjust as desired.

  if (arg == endptr) return false; // no conversion occurred.
  if (errno == ERANGE) return false; // outside `long` range
  if (value > INT_MAX || value < INT_MIN) return false; // outside `int` range
  if (*endptr != '\0') return false; // Extra junk at end

  return true;
}



  for (i=1; i<argc; i++) {
    if (!is_int(argv+i)) {
      printf("Incorrect input\n");
      return 1;
    }
  } 

Research strtol() for more details.


Alternatively one could simply look for an optional sign followed by digits if any integer is OK, even big ones.

bool is_integer(const char *arg) {
  if (*arg == '-' || *arg == '+') arg++;

  bool digit_found = false;
  while (isdigit((unsigned char) *arg)) {
     arg++;
     digit_found = true;
  }

  return *arg == '\0' && digit_found;
}

atoi(*(argv+i)) should generate a warning. Enable all warnings to save time. atoi() expects a pointer to a string.

Upvotes: 1

Related Questions