Read an Integer from the User, Part 2

Dave Sinkula Dave Sinkula is offline Offline Aug 10th, 2005, 1:21 pm |
0
Some issues, such as leading whitespace and trailing characters that cannot be part of a number, were not handled in Read an Integer from the User, Part 1. Here such issues receive lip service.
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. int mygeti(int *result)
  5. {
  6. char c, buff [ 13 ]; /* signed 32-bit value, extra room for '\n' and '\0' */
  7. return fgets(buff, sizeof buff, stdin) && !isspace(*buff) &&
  8. sscanf(buff, "%d%c", result, &c) == 2 && (c == '\n' || c == '\0');
  9. }
  10.  
  11. int main(void)
  12. {
  13. int value;
  14. do {
  15. fputs("Enter an integer: ", stdout);
  16. fflush(stdout);
  17. } while ( !mygeti(&value) );
  18. printf("value = %d\n", value);
  19. return 0;
  20. }
  21.  
  22. /* my output
  23. Enter an integer: one
  24. Enter an integer:
  25. Enter an integer: f123
  26. Enter an integer: 123f
  27. Enter an integer: 123
  28. Enter an integer: 123
  29. Enter an integer: 1.23
  30. Enter an integer: -42
  31. value = -42
  32. */
  33.  
  34. /* note: this line in the above has a space character following the 123
  35. Enter an integer: 123
  36. */
0
drxs33 drxs33 is offline Offline | Mar 29th, 2009
Thank you sir dave.. it helped me alot.. thanks!
 
 

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC