Search code examples
cintegervalidationstrtol

Convert a string to int (But only if really is an int)


In college I was asked if our program detects if the string enter from command line arguments is a integer which it did not(./Program 3.7). Now I am wondering how I can detect this. So input as for example a is invalid which atoi detects, but input like for example 3.6 should be invalid but atoi will convert this to an integer.

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc > 1) {
        int number = atoi(argv[1]);
        printf("okay\n");
    }
}

But offcourse okay should only be printed if argv[1] is really an integer. Hope my question is clear. Many thanks.


Solution

  • Have a look at strtol.

    If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, however, strtol() stores the original value of str in *endptr. (Thus, if *str is not \0' but **endptr is \0' on return, the entire string was valid.)

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[]) {
      if (argc > 1) {
        char* end;
        long number = strtol(argv[1], &end, 0);
        if (*end == '\0')
          printf("okay\n");
      }
    }