Question

I would like to be able to take any unsigned long integer as an argument for my program. Consider this simplified version.

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

 unsigned long int steps;

 sscanf(argv[1], "%lu", &steps);

 printf("n is %lu \n",steps);

}

The problem I have is that if you give it -10 it will return ULONG_MAX - 10, is there an elegant solution that will return me the integer when in range and 0 for all other cases. From what I read I might need to use fgets with regex somehow, is perhaps that the best solution?

Was it helpful?

Solution

You can use atol() and check for the returned value. Here is a little example:

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char **argv)
{
  unsigned long int steps = 0;

  if (argc > 1)
    {
      if (atol(argv[1]) > 0)
        steps = atol(argv[1]);
    }

  printf("%lu\n", steps);

  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top