parsing - Command line argument integer error checking in C -


i'm trying parse integer arguments given on command line c. given input this:

a.out 2

very simple. cannot figure out how have error checking on this. example each of following runs should throw error:

a.out 2hi

a.out 9hello

a.out 4x

the error handling have implemented catches non-integer characters in front of integer (e.g. "> a.out hi4") using sscanf. atoi() , strtol() don't work because parse integer value off front of argument. appreciated!

use strtol() , check end of converted end of string:

char *end;  errno = 0; long l = strtol(argv[1], &end, 10);  // 0 if want octal/hex/decimal  if (end == argv[i] || *end != '\0' || ((l == long_min || l == long_max) && errno == erange))     …report problems… …either use l long, or check in range int_min..int_max 

this skip quietly on leading blanks. if that's problem, can check them too:

if (!isdigit((unsigned char)argv[i]) && argv[i] != '+' && argv[i] != '-')    …first character isn't part of decimal number… 

see also:


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -