Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1.        int
  2.        main(int argc, char *argv[])
  3.        {
  4.            int base;
  5.            char *endptr, *str;
  6.            unsigned long val;
  7.  
  8.            if (argc < 2) {
  9.                fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
  10.                exit(EXIT_FAILURE);
  11.            }
  12.  
  13.            str = argv[1];
  14.            base = 10;
  15.  
  16.            errno = 0;    /* To distinguish success/failure after call */
  17.            val = strtoul(str, &endptr, base);
  18.  
  19.            /* Check for various possible errors */
  20.  
  21.            if ((errno == ERANGE && (val == ULONG_MAX))   || (errno != 0 && val == 0)) {
  22.                perror("strtoul");
  23.                exit(EXIT_FAILURE);
  24.            }
  25.  
  26.            if (!isdigit(str[0])) {
  27.                fprintf(stderr,"- character were found\n");
  28.                exit(EXIT_FAILURE);
  29.            }
  30.  
  31.            if (endptr == str) {
  32.                fprintf(stderr, "No digits were found\n");
  33.                exit(EXIT_FAILURE);
  34.            }
  35.  
  36.            /* If we got here, strtol() successfully parsed a number */
  37.  
  38.            printf("strtul() returned %lu\n", val);
  39.  
  40.            if (*endptr != '\0')        /* Not necessarily an error... */
  41.                printf("Further characters after number: %s\n", endptr);
  42.  
  43.            exit(EXIT_SUCCESS);
  44.        }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement