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

Dave Sinkula Dave Sinkula is offline Offline Aug 14th, 2005, 1:00 pm |
0
Some issues, such as leading whitespace and trailing characters that cannot be part of a number, were not handled in Read a Floating-Point Value from the User, Part 1. Here such issues receive lip service.

See also Read a Floating-Point Value from the User, Part 3.
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. int mygetd(double *result)
  5. {
  6. char c, buff [ 32 ];
  7. return fgets(buff, sizeof buff, stdin) && !isspace(*buff) &&
  8. sscanf(buff, "%lf%c", result, &c) == 2 && (c == '\n' || c == '\0');
  9. }
  10.  
  11. int main(void)
  12. {
  13. double value;
  14. do
  15. {
  16. fputs("Enter a floating-point number: ", stdout);
  17. fflush(stdout);
  18. } while ( !mygetd(&value) );
  19. printf("value = %g\n", value);
  20. return 0;
  21. }
  22.  
  23. /* my output
  24. Enter a floating-point number: one
  25. Enter a floating-point number:
  26. Enter a floating-point number: f12.3
  27. Enter a floating-point number: -45.67
  28. value = -45.67
  29.  
  30. Enter a floating-point number: -12.3f
  31. Enter a floating-point number: 125 help
  32. Enter a floating-point number: 1.2.3
  33. Enter a floating-point number: 1.23
  34. value = 1.23
  35. */

Message:


Thread Tools Search this Thread



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

©2003 - 2009 DaniWeb® LLC