Read an Integer from the User, Part 3

Please support our C advertiser: Programming Forums
Dec 22nd, 2005
Views: 3,642
Thread Rating: 2 votes, 4.0000 average.
AddThis Social Bookmark Button
This is a strtol version of Read an Integer from the User, Part 2.
c Syntax
  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. */

Only community members can submit or comment on code snippets. You must register or log in to contribute.

Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 1:07 pm.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC