From: W. Trevor King Date: Mon, 11 Feb 2013 16:30:34 +0000 (-0500) Subject: safe-strtod.c: Split safe_strtod() into a library X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=7093391f3ce217ee1d2af0054c147e758e1b2582;p=assignment-template.git safe-strtod.c: Split safe_strtod() into a library Cherry pick from my phys305/zeta-and-step solutions. --- diff --git a/safe-strtod.c b/safe-strtod.c new file mode 100644 index 0000000..8396a0e --- /dev/null +++ b/safe-strtod.c @@ -0,0 +1,41 @@ +/* +Safe string-to-double conversion + +Copyright (C) 2013 W. Trevor King + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include /* for strtod(), exit(), EXIT_* */ +#include /* for stderr, *printf(), perror() */ +#include /* for errno */ +#include "safe-strtod.h" /* check safe_strtod() declaration */ + +double safe_strtod(const char *str, const char *name) +{ + char *endptr; + double x = strtod(str, &endptr); + + if (errno) { + fprintf(stderr, "error converting %s to a double for %s:\n", str, name); + perror("strtod"); + exit(EXIT_FAILURE); + } + if (endptr[0] != '\0') { + fprintf(stderr, "error converting %s to a double for %s:\n", str, name); + fprintf(stderr, "leftover characters: %s\n", endptr); + exit(EXIT_FAILURE); + } + return x; +} diff --git a/safe-strtod.h b/safe-strtod.h new file mode 100644 index 0000000..e50a9c3 --- /dev/null +++ b/safe-strtod.h @@ -0,0 +1,25 @@ +/* +Safe string-to-double conversion + +Copyright (C) 2013 W. Trevor King + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#ifndef _STRTOD_SAFE_H_ +#define _STRTOD_SAFE_H_ + +double safe_strtod(const char *str, const char *name); + +#endif /* _STRTOD_SAFE_H_ */