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

Please support our C advertiser: Programming Forums
Nov 20th, 2006
Views: 2,895
Thread Rating: 1 votes, 5.0000 average.
AddThis Social Bookmark Button
This snippet uses strtod to be a little more stringent.
c Syntax
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <ctype.h>
  4.  
  5. int mygetd(double *result)
  6. {
  7. char *end, buff [ 32 ];
  8. return fgets(buff, sizeof buff, stdin) && !isspace(*buff) &&
  9. (*result = strtod(buff, &end)), ( *end == '\n' || *end == '\0' );
  10. }
  11.  
  12. int main(void)
  13. {
  14. double value = -12.3;
  15. do
  16. {
  17. fputs("Enter a floating-point number: ", stdout);
  18. fflush(stdout);
  19. } while ( !mygetd(&value) );
  20. printf("value = %g\n", value);
  21. return 0;
  22. }
  23.  
  24. /* my output
  25. Enter a floating-point number: one
  26. Enter a floating-point number:
  27. Enter a floating-point number: f12.3
  28. Enter a floating-point number: -45.67
  29. value = -45.67
  30.  
  31. Enter a floating-point number: -12.3f
  32. Enter a floating-point number: 125 help
  33. Enter a floating-point number: 1.2.3
  34. Enter a floating-point number: 1.23
  35. value = 1.23
  36. */

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:03 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