Read a Floating-Point Value from the User, Part 1

Dave Sinkula Dave Sinkula is offline Offline Aug 14th, 2005, 12:27 pm |
0
Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than scanf("%lf", &n), but not bulletproof. It is meant to be a simple but relatively safe demonstration. Note also that there would be slight differences for using float instead of double.

The function mygetd reads user input from the stdin into a string using fgets. Then it attempts to convert this string to a double 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 a Floating-Point Value from the User, Part 2 and Read a Floating-Point Value from the User, Part 3.
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2.  
  3. int mygetd(double *result)
  4. {
  5. char buff [ 32 ]; /* modify array size to suit your needs */
  6. return fgets(buff, sizeof buff, stdin) && sscanf(buff, "%lf", result) == 1;
  7. }
  8.  
  9. int main(void)
  10. {
  11. double value;
  12. do {
  13. fputs("Enter a floating-point number: ", stdout);
  14. fflush(stdout);
  15. } while ( !mygetd(&value) );
  16. printf("value = %g\n", value);
  17. return 0;
  18. }
  19.  
  20. /* my output
  21. Enter a floating-point number: one
  22. Enter a floating-point number:
  23. Enter a floating-point number: f12.3
  24. Enter a floating-point number: -45.67
  25. value = -45.67
  26.  
  27. Enter a floating-point number: -12.3f
  28. value = -12.3
  29.  
  30. Enter a floating-point number: 125 help
  31. value = 125
  32. */

Message:


Thread Tools Search this Thread



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

©2003 - 2009 DaniWeb® LLC