| | |
Read a Floating-Point Value from the User, Part 1
Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than
The function
Leading whitespace, and other trailing characters are some things not handled. Those issues are handled in Read a Floating-Point Value from the User, Part 2 and Read a Floating-Point Value from the User, Part 3.
scanf("%lf", &n), but not bulletproof. It is meant to be a simple but relatively safe demonstration. Note also that there would be slight differences for using float instead of double.The function
mygetd reads user input from the stdin into a string using fgets. Then it attempts to convert this string to a double using sscanf. If both functions succeed, a 1 is returned; if either fails, a 0 is returned.Leading whitespace, and other trailing characters are some things not handled. Those issues are handled in Read a Floating-Point Value from the User, Part 2 and Read a Floating-Point Value from the User, Part 3.
#include <stdio.h> int mygetd(double *result) { char buff [ 32 ]; /* modify array size to suit your needs */ return fgets(buff, sizeof buff, stdin) && sscanf(buff, "%lf", result) == 1; } int main(void) { double value; do { fputs("Enter a floating-point number: ", stdout); fflush(stdout); } while ( !mygetd(&value) ); printf("value = %g\n", value); return 0; } /* my output Enter a floating-point number: one Enter a floating-point number: Enter a floating-point number: f12.3 Enter a floating-point number: -45.67 value = -45.67 Enter a floating-point number: -12.3f value = -12.3 Enter a floating-point number: 125 help value = 125 */
Similar Threads
- Code Snippet: Read an Integer from the User, Part 2 (C)
- how to read a binary file holding floating-point values (VB.NET)
- FLOATING POINT.......Please (C++)
- Code Snippet: Read an Integer from the User, Part 1 (C)
- floating point (C++)
| Thread Tools | Search this Thread |
#include adobe ansi api array asterisks binarysearch changingto char character cm copyimagefile cprogramme creafecopyofanytypeoffileinc createcopyoffile csyntax database directory dynamic execv feet fgets file fork forloop frequency function getlasterror givemetehcodez global grade graphics gtkgcurlcompiling hacking hardware highest histogram i/o include incrementoperators infiniteloop input interest kernel keyboard kilometer license linked linkedlist linux linuxsegmentationfault list locate logical_drives looping loopinsideloop. lowest match matrix meter microsoft motherboard mqqueue mysql number odf opensource owf pattern pdf performance pointer posix probleminc process program programming radix recursion recv repetition research reversing scanf segmentationfault sequential shape socket socketprograming standard string systemcall threads turboc unix user voidmain() wab windows.h windowsapi



