/* ** $Id: tol.c 772 2008-02-15 23:54:05Z phf $ ** ** Example where pointers are handy: How to properly (well, ** almost properly anyway) use the strtol() function. Lots ** of older material uses atoi(), but you should not do so ** anymore these days. :-) ** ** Some atoi() man pages say that atoi() is about the same ** thing as ** ** ... (int) strtol(nptr, NULL, 10) ... ** ** and that's quite close. But of course we want to take ** advantage of all strtol() has to offer, which includes ** decent error checking ("is it really an integer?"). ** ** The program below will go through the command line and ** try to convert every argument into a long (assuming we ** use base 10!). It'll tell us (as part of this) which ** arguments could be converted flawlessly. Watch for the ** double-pointer stunts! :-) */ #include #include int main(int argc, char *argv[]) { // go through arguments (except program name) one by one for(int i = 1; i < argc; i++) { // just for debugging... printf("argv[%d] == \"%s\"\n", i, argv[i]); // set up the "error pointer" for strtol() char *err; // call strtol(); we need to pass the *address* of the // error pointer, since strtol() must be able to set it // for us; it'll be made to point to the first char in // the string that could *not* be converted using the // given base; so if we are completely successful, it // will point to the '\0' at the end; if we succeed to // some extent, it'll point into the string somewhere; // if we are not successful at all, it'll point to the // first char; kinda cool... :-) long n = strtol(argv[i], &err, 10); // print the value we got back for this argument string printf("n == %ld\n", n); // print the value (and the string) we get trough err printf("err == %p or \"%s\"\n", err, err); if (*err == '\0') { // we know that everything was good if we point to '\0' printf("Sunny day, we converted that one flawlessly.\n"); } else if (err == argv[i]) { // we know all is lost if we point to the beginning printf("Stormy night, can't do anything with that!!!\n"); } else { // we're (hopefully) somewhere in the middle of the string, // so there was some trash we couldn't convert at the end printf("Cloudy dusk, got some stuff done but not all!\n"); } } }