Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #define EPARSE ERANGE + 1
- int sumacifp(int n) {
- int t = 0;
- int sum = 0;
- while (n)
- {
- ++t;
- if (t % 2 == 0)
- {
- sum += n % 10;
- }
- n /= 10;
- }
- if (t < 2)
- {
- return -1;
- }
- return sum;
- }
- long int parse_long_int (const char* s) {
- char* str_end;
- long int n = strtol(s, &str_end, 10);
- /* if after the conversion str_end is not at the
- * end of the string, then the string is not a number
- */
- if (*str_end != '\0') {
- errno = EPARSE;
- return 0;
- }
- if (errno == ERANGE) {
- return 0;
- }
- return n;
- }
- void validate_arguments (int nargs, char* args[]) {
- const char how_to_use[] = "Usage: %s <num1>\nWhere <num1> is non-negative integer\n";
- const char too_many_args[] = "Too many arguments";
- const char too_few_args[] = "Not enough arguments";
- const char invalid_first[] = "Invalid argument";
- if (nargs < 2) {
- fprintf(stderr, "%s\n", too_few_args);
- fprintf(stderr, how_to_use, args[0]);
- exit(EXIT_FAILURE);
- }
- if (nargs > 2) {
- fprintf(stderr, "%s\n", too_many_args);
- fprintf(stderr, how_to_use, args[0]);
- exit(EXIT_FAILURE);
- }
- const char* arg = args[1];
- long int number = parse_long_int(arg);
- if (errno == ERANGE || errno == EPARSE || number < 0) {
- fprintf(stderr, "%s\n", invalid_first);
- fprintf(stderr, how_to_use, args[0]);
- exit(EXIT_FAILURE);
- }
- }
- int main (int nargs, char* args[]) {
- validate_arguments(nargs, args);
- long int number = parse_long_int(args[1]);
- long int sum = sumacifp(number);
- printf("%ld\n", sum);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement