DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   Code Snippet: Read a Floating-Point Value from the User, Part 3 (http://www.daniweb.com/forums/thread216829.html)

Dave Sinkula Nov 20th, 2006 11:44 pm
Read a Floating-Point Value from the User, Part 3
 
This snippet uses strtod to be a little more stringent.

  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. */
bemboysms Jul 30th, 2009 11:11 pm
how about reading a temperature in degree celsius and then conbert it to fahrenheit?


All times are GMT -4. The time now is 1:08 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC