Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.75 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <string.h>
  5.  
  6. #define EPARSE ERANGE + 1
  7.  
  8. int sumacifp(int n) {
  9. int t = 0;
  10. int sum = 0;   
  11. while (n)
  12.     {
  13.     ++t;
  14. if (t % 2 == 0)
  15. {
  16. sum += n % 10;
  17. }
  18. n /= 10;
  19.     }
  20. if (t < 2)
  21. {
  22. return -1;
  23. }
  24. return sum;
  25. }
  26.  
  27. long int parse_long_int (const char* s) {
  28.     char* str_end;
  29.     long int n = strtol(s, &str_end, 10);
  30.     /* if after the conversion str_end is not at the
  31.      * end of the string, then the string is not a number
  32.      */
  33.     if (*str_end != '\0') {
  34.         errno = EPARSE;
  35.         return 0;
  36.     }
  37.     if (errno == ERANGE) {
  38.         return 0;
  39.     }
  40.  
  41.     return n;
  42. }
  43.  
  44. void validate_arguments (int nargs, char* args[]) {
  45.     const char how_to_use[] = "Usage: %s <num1>\nWhere <num1> is non-negative integer\n";
  46.     const char too_many_args[] = "Too many arguments";
  47.     const char too_few_args[] = "Not enough arguments";
  48.     const char invalid_first[] = "Invalid argument";
  49.  
  50.     if (nargs < 2) {
  51.         fprintf(stderr, "%s\n", too_few_args);
  52.         fprintf(stderr, how_to_use, args[0]);
  53.         exit(EXIT_FAILURE);
  54.     }
  55.  
  56.     if (nargs > 2) {
  57.         fprintf(stderr, "%s\n", too_many_args);
  58.         fprintf(stderr, how_to_use, args[0]);
  59.         exit(EXIT_FAILURE);
  60.     }
  61.    
  62.     const char* arg = args[1];
  63.  
  64.  
  65.     long int number = parse_long_int(arg);
  66.     if (errno == ERANGE || errno == EPARSE || number < 0) {
  67.         fprintf(stderr, "%s\n", invalid_first);
  68.         fprintf(stderr, how_to_use, args[0]);
  69.         exit(EXIT_FAILURE);
  70.     }
  71. }
  72.  
  73.  
  74. int main (int nargs, char* args[]) {
  75.     validate_arguments(nargs, args);
  76.  
  77.     long int number = parse_long_int(args[1]);
  78.  
  79.     long int sum = sumacifp(number);
  80.     printf("%ld\n", sum);
  81.  
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement