Read an Integer from the User, Part 1

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Dave Sinkula Dave Sinkula is offline Offline May 20th, 2005, 2:11 pm |
0
Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than scanf("%d", &n), but not bulletproof. It is meant to be a simple but relatively safe demonstration.

The function mygeti reads user input from the stdin into a string using fgets. Then it attempts to convert this string to an integer using sscanf. If both functions succeed, a 1 is returned; if either fails, a 0 is returned.

Leading whitespace, and other trailing characters are some things not handled. Those issues are handled in Read an Integer from the User, Part 2. Reading a Floating-Point Value from the User can be done similarly.
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2.  
  3. int mygeti(int *result)
  4. {
  5. char buff [ 13 ]; /* signed 32-bit value, extra room for '\n' and '\0' */
  6. return fgets(buff, sizeof buff, stdin) && sscanf(buff, "%d", result) == 1;
  7. }
  8.  
  9. int main(void)
  10. {
  11. int value;
  12. do {
  13. fputs("Enter an integer: ", stdout);
  14. fflush(stdout);
  15. } while ( !mygeti(&value) );
  16. printf("value = %d\n", value);
  17. return 0;
  18. }
  19.  
  20. /* my output
  21. Enter an integer: one
  22. Enter an integer:
  23. Enter an integer: 42
  24. value = 42
  25.  
  26. Enter an integer: 24f
  27. value = 24
  28.  
  29. Enter an integer: 125 help
  30. value = 125
  31. */

Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC