Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than
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
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.