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

Dave Sinkula Dave Sinkula is offline Offline Nov 20th, 2006, 11:44 pm |
0
This snippet uses strtod to be a little more stringent.
Quick reply to this message  
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. */
-2
bemboysms bemboysms is offline Offline | Jul 30th, 2009
how about reading a temperature in degree celsius and then conbert it to fahrenheit?
 
 

Message:


Thread Tools Search this Thread



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

©2003 - 2009 DaniWeb® LLC