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

Untitled

By: a guest on Apr 26th, 2012  |  syntax: None  |  size: 0.70 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. C - Check that an int read by scanf is in the range of the integers
  2. int e_1;
  3. char c[1];
  4. // noNeedToCleanBuffer is used to avoid buffer cleaning the first time.
  5. int noNeedToCleanBuffer = 1;
  6. do {
  7.     // Clears the buffer.
  8.     if (!noNeedToCleanBuffer)
  9.         while ((c[0] = getchar()) != 'n') ;
  10.  
  11.     noNeedToCleanBuffer = 0;
  12.     printf("Input an integer value: n");
  13.     e_1 = scanf("%d", &n);  
  14.  
  15.     c[0] = getchar();
  16. } while ((e_1 != 1 && c[0] != 10) || (e_1 == 1 && c[0] != 10));
  17.        
  18. num = INT_MAX;
  19. i = 0;
  20.  
  21. while(num != 0){
  22.     str[i] = num % 10;
  23.     num = num / 10;
  24.     i++;
  25. }
  26.        
  27. int foo = /* some value to test */;
  28. long bar = (long)foo;
  29.  
  30. if ( (bar < (long)INT_MIN) || (bar > (long)INT_MAX) ) return false;