JayB
JayB

Reputation: 397

Checking if command line input is valid integer (C)

I'm trying to verify that my program's user enters a valid integer in the command line. I've run into a problem: It rejects ALL input.

Here's what I have

// Make sure input is a valid int
char *ptr = NULL;
long int input = strtol(argv[i+1], &ptr, 10);
if(ptr == NULL){
    userMinInt = input;
    minIntSet = true;    
}
else
    fprintf(stderr, "You must enter a valid integer for <min-int>. Using default value of %ld\n", minInt);

Upvotes: 1

Views: 1314

Answers (2)

chux
chux

Reputation: 153338

Code is checking if the end-pointer is NULL. Instead, code should check for:

1) Does the end-pointer point to the null character '\0'?
2) Does the end-pointer differ from the start?

Additional checks below:

char *start = argv[i+1];  // maybe should be argv[i]
char *ptr;
// set errno to 0 for subsequent check
errno = 0;
long int input = strtol(start, &ptr, 10);
if (ptr == start) {
  fprintf(stderr, "No conversion done.\n");
}
else if (*ptr != 0) {
  fprintf(stderr, "Extra data after the number.\n");
}
else if (errno) {
  fprintf(stderr, "Number outside long range.\n");
}
else if (input < INT_MIN || input > INT_MAX) {
  fprintf(stderr, "Number %ld outside int range.\n", input);
}
else {
  printf("Number is %d.\n", (int) input);
}

Upvotes: 1

JayB
JayB

Reputation: 397

Thanks to peter, I've solved the problem. Here is the new working code:

// Make sure input is a valid int
char *ptr = NULL;
long int input = strtol(argv[i+1], &ptr, 10);
if(ptr != NULL && *ptr == (char)0){
    userMinInt = input;
    minIntSet = true;
}
else
    fprintf(stderr, "You must enter a valid integer for <min-int>. Using default value of %ld\n", minInt);

Upvotes: 0

Related Questions