944,127 Members | Top Members by Rank

Ad:
  • C Code Snippet
  • Views: 4555
  • C RSS
0

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

by on Nov 20th, 2006
This snippet uses strtod to be a little more stringent.
C Code Snippet (Toggle Plain Text)
  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. */
Comments on this Code Snippet
Jul 30th, 2009
-2

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

how about reading a temperature in degree celsius and then conbert it to fahrenheit?
Newbie Poster
bemboysms is offline Offline
2 posts
since Jul 2009
Message:
Previous Thread in C Forum Timeline: Start Learning C
Next Thread in C Forum Timeline: How to convert char string of Hex characters to unsigned char string of binary data





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC