diff --git a/Makefile b/Makefile index a225d93..c8d03b7 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := 9.0.3 +VERSION := 9.1.0 MAJOR_VERSION := $(shell echo $(VERSION) | head -c 1) # installation directory (/usr/local by default) diff --git a/src/cs50.c b/src/cs50.c index 5feac60..a51eec1 100644 --- a/src/cs50.c +++ b/src/cs50.c @@ -397,6 +397,43 @@ long get_long(const char *format, ...) } } +/** + * Prompts user for a line of text from standard input and returns the + * equivalent long long; if text does not represent a long long in + * [-2^63, 2^63 - 1) or would cause underflow or overflow, user is + * prompted to retry. If line can't be read, returns LLONG_MAX. + */ +long long get_long_long(const string format, ...) +{ + va_list ap; + va_start(ap, format); + + // Try to get a long long from user + while (true) + { + // Get line of text, returning LLONG_MAX on failure + string line = get_string(&ap, format); + if (line == NULL) + { + va_end(ap); + return LLONG_MAX; + } + + // Return a long long if only a long long (in range) was provided + if (strlen(line) > 0 && !isspace((unsigned char) line[0])) + { + char *tail; + errno = 0; + long long n = strtoll(line, &tail, 10); + if (errno == 0 && *tail == '\0' && n < LLONG_MAX) + { + va_end(ap); + return n; + } + } + } +} + /** * Called automatically after execution exits main. */ diff --git a/src/cs50.h b/src/cs50.h index 2b9d18b..b284ba2 100644 --- a/src/cs50.h +++ b/src/cs50.h @@ -94,6 +94,14 @@ int get_int(const char *format, ...) __attribute__((format(printf, 1, 2))); */ long get_long(const char *format, ...) __attribute__((format(printf, 1, 2))); +/** + * Prompts user for a line of text from standard input and returns the + * equivalent long long; if text does not represent a long long in + * [-2^63, 2^63 - 1) or would cause underflow or overflow, user is + * prompted to retry. If line can't be read, returns LLONG_MAX. + */ +long long get_long_long(const string format, ...) __attribute__((format(printf, 1, 2))); + /** * Prompts user for a line of text from standard input and returns * it as a string (char *), sans trailing line ending. Supports