Advertisement
N1K003

Untitled

Feb 15th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.03 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdbool.h>
  4.  
  5. void usage()
  6. {
  7.         printf("Provide string number(only 0-9 and '-' sign) to parse into integer!\n");
  8. }
  9.  
  10. int toInt(const char c) {
  11.         if(c > '9' || c < '0')
  12.                 return -1;
  13.         return c - '0';
  14. }
  15.  
  16. int main(int argc, char** argv)
  17. {
  18.         if (argc < 2) {
  19.                 usage();
  20.                 return -1;
  21.         }
  22.  
  23.         bool minus = argv[1][0] == '-';
  24.         printf("Minus: %s\n", minus == true ? "true" : "false");
  25.  
  26.         int number = 0;
  27.         int len = strlen(argv[1]);
  28.  
  29.         printf("Len %d\n", len);
  30.  
  31.         for (int i = minus ? 1 : 0; i < len; i++) {
  32.                 int num = toInt(argv[1][i]);
  33.  
  34.                 if (num == -1) {
  35.                         usage();
  36.                         return -2;
  37.                 }
  38.  
  39.                 number = number * 10 + num;
  40.         }
  41.  
  42.         if (minus) {
  43.                 number *= -1;
  44.         }
  45.  
  46.         printf("input: %s, numer: %d\n", argv[1], number);
  47.  
  48. return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement