DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   Code Snippet: Read an Integer from the User, Part 3 (http://www.daniweb.com/forums/thread216679.html)

Dave Sinkula Dec 22nd, 2005 1:20 pm
Read an Integer from the User, Part 3
 
This is a strtol version of Read an Integer from the User, Part 2.

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4.  
  5. int mygeti(int *result)
  6. {
  7. char *end, buff [ 13 ];
  8. fgets(buff, sizeof buff, stdin);
  9. *result = strtol(buff, &end, 10);
  10. return !isspace(*buff) && end != buff && (*end == '\n' || *end == '\0');
  11. }
  12.  
  13. int main(void)
  14. {
  15. int value;
  16. do
  17. {
  18. fputs("Enter an integer: ", stdout);
  19. fflush(stdout);
  20. } while ( !mygeti(&value) );
  21. printf("value = %d\n", value);
  22. return 0;
  23. }
  24.  
  25. /* my output
  26. Enter an integer: one
  27. Enter an integer:
  28. Enter an integer: f123
  29. Enter an integer: 123f
  30. Enter an integer: 123
  31. Enter an integer: 123
  32. Enter an integer: 1.23
  33. Enter an integer: -42
  34. value = -42
  35. */

All times are GMT -4. The time now is 8:07 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC