I'm trying to understand the strtod()
function, and how I can handle any user input given to the function. I assume I tested for everything, however I am hoping for a review to make sure and to catch anything I missed. (I know I should separate everything into functions, however, I am just trying to understand the nature of the function, therefore I left everything in main
.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>
#include <stdbool.h>
/*@param MAXSIZE max number of chars that are converted to a 64bit double*/
#define MAXSIZE 1077
int main() {
char str[MAXSIZE];
printf("Enter a rational number: ");
for (;;) {
if (fgets(str, sizeof str, stdin) != NULL) {
if (strchr(str, '\n')) {
str[strcspn(str, "\n")] = '\0';
}
if (str[0] != '\0') {
break;
}
printf("\nTry again: ");
}
}
char* endptr = NULL;
errno = 0;
double number = strtod(str, &endptr);
//passes over trailing whitespace
for (; isspace(*endptr); ++endptr);
if (errno == ERANGE) {
fprintf(stderr, "Error out of range...\n");
}
else if (*endptr != '\0') {
fprintf(stderr, "error could not convert: %s\n", str);
}
else {
printf("Your string was converted into the rational number: %lf\n", number);
}
printf("Your string was: %s\n", str);
printf("Press any key to continue...\n");
getch();
}
1/3
here. "Decimal" may be a better choice. (not an answer, as it's tangential to the requested review) – Toby Speight 21 hours ago