Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 1.68 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3. #include <limits.h>
  4.  
  5. int digits_in(int number)
  6. {
  7.     int log10i = 0;
  8.    
  9.     while (number /= 10)
  10.         ++log10i;
  11.    
  12.     return log10i + 1;
  13. }
  14.  
  15. bool is_delim(int c)
  16. {
  17.     return (c == ' ') || (c == '\t') || (c == '\n') || (c == ',');
  18. }
  19.  
  20.  
  21. bool is_digit(int c)
  22. {
  23.     return (c >= '0') && (c <= '9');
  24. }
  25.  
  26. int main(void) {
  27.     int c, in_word = false, digits_only = true;
  28.     int number = 0, tmp_number = 0, sign = +1, overflow = false;
  29.    
  30.     while ((c = getchar()) != EOF)
  31.     {
  32.         if (is_delim(c))
  33.         {
  34.             if (in_word && digits_only)
  35.             {
  36.                 if (!overflow) {
  37.                     if (sign < 0)
  38.                     {
  39.                         printf("-");
  40.                     }
  41.                    
  42.                     printf("out: %0*d\n", digits_in(INT_MAX), number);
  43.                     sign = +1;
  44.                 }
  45.             }
  46.            
  47.             number = 0;
  48.             digits_only = true;
  49.             overflow = false;
  50.             in_word = false;
  51.         }
  52.         else
  53.         {
  54.             if (is_digit(c) && digits_only)
  55.             {
  56.                 tmp_number = number*10 + (c - '0');
  57.                
  58.                 if (tmp_number * number < 0) {
  59.                     overflow = true;
  60.                 }
  61.                
  62.                 number = tmp_number;
  63.             }
  64.             else if (!in_word && (c == '-'))
  65.             {
  66.                 sign = -1;
  67.             }
  68.             else
  69.             {
  70.                 digits_only = false;
  71.                 sign = +1;
  72.             }
  73.             in_word = true;
  74.         }
  75.     }
  76.    
  77.     return 0;
  78. }