/*
-Safe string-to-double conversion
+Safe string-to-* conversion
Copyright (C) 2013 W. Trevor King
#include <stdlib.h> /* for strtod(), exit(), EXIT_* */
#include <stdio.h> /* for stderr, *printf(), perror() */
#include <errno.h> /* for errno */
-#include "safe-strtod.h" /* check safe_strtod() declaration */
+#include "safe-strto.h" /* check safe_strto*() declarations */
+
+long int safe_strtol(const char *str, int base, const char *name)
+{
+ char *endptr;
+ long int x = strtol(str, &endptr, base);
+
+ if (errno) {
+ fprintf(stderr, "error converting %s to a long integer for %s:\n",
+ str, name);
+ perror("strtol");
+ exit(EXIT_FAILURE);
+ }
+ if (endptr[0] != '\0') {
+ fprintf(stderr, "error converting %s to a long integer for %s:\n",
+ str, name);
+ fprintf(stderr, "leftover characters: %s\n", endptr);
+ exit(EXIT_FAILURE);
+ }
+ return x;
+}
double safe_strtod(const char *str, const char *name)
{
/*
-Safe string-to-double conversion
+Safe string-to-* conversion
Copyright (C) 2013 W. Trevor King
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#ifndef _STRTOD_SAFE_H_
-#define _STRTOD_SAFE_H_
+#ifndef _SAFE_STRTO_H_
+#define _SAFE_STRTO_H_
+long int safe_strtol(const char *str, int base, const char *name);
double safe_strtod(const char *str, const char *name);
-#endif /* _STRTOD_SAFE_H_ */
+#endif /* _SAFE_STRTO_H_ */