Advertisement
STANAANDREY

sum from cl args

Oct 18th, 2024
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.47 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <ctype.h>
  5.  
  6. int main(int argc, char *argv[]) {
  7.   if (argc & 1) {
  8.     fprintf(stderr, "arg error!\n");
  9.     exit(-1);
  10.   }
  11.  
  12.   int sum = strtol(argv[1], NULL, 10);
  13.   for (int i = 2; i < argc; i++) {
  14.     int sign = 1, nr;
  15.     if (*argv[i] == '-') {
  16.       sign = -1;
  17.     }
  18.     i++;
  19.     nr = strtol(argv[i], NULL, 10);
  20.     nr *= sign;
  21.     sum += nr;
  22.   }
  23.   printf("result: %d\n", sum);
  24.   return 0;
  25. }
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement