getopt - C Using isdigit to check if optarg is a digit -


if optarg (the argument after flag -s, getop library) isn't digit, want error message printed , program terminated, , if digit, size needs set optarg. problem have while command -s r hit error message, -s 2 also, meaning it's interpreting 2 string.

debugging -s 2

#1 printf("%d",atoi(optarg)); #2 printf("%d",isdigit(atoi(optarg))); 

i int value 2 line #1, , int value of 0 line #2.

so wondering why isdigit(atoi(optarg))) gives me 0, when atoi(optarg) gives me int. there better way check if optarg int?

int main (int argc, char *argv[]){   int size; char option; size = 0; const char *optstring; optstring = "rs:pih";   while ((option = getopt(argc, argv, optstring)) != eof) {     switch (option) {         case 'r':             type_set = 1;             break;         **case 's':             capacity_set = 1;             if(isdigit(atoi(optarg))==0){                 fprintf(stderr,"argument after -s needs int\n");                 return 0;             }**             else{                 size = atoi(optarg);             }              break;          default{         return 0;         }   

isdigit takes character , tells if digit. atoi takes string (char *) , returns number string represents. when call isdigit(atoi(... you're taking number , treating character. since charater codes digits 48..57, number other 1 of return false.

you want isdigit(*optarg) -- tell if first character of argument (string) digit character. of course, looks @ first character, might want isdigit(optarg[0]) && optarg[1] == 0 instead.

if want accept number rather digit (and number), strtol works better atoi allows check failures. like:

char *end; errno = 0; size = strtol(optarg, &end, 10); while (isspace(*end)) ++end; if (errno || *end) {     // error occurred on conversion, or there cruft     // after number in argument.     fprintf(stderr,"argument after -s needs int\n");     return 0; } 

Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -