From 51b00fb57a1aaf402817038b2fe582d26b4c299b Mon Sep 17 00:00:00 2001 From: TheUltimateOptimist Date: Sun, 28 Jan 2024 01:00:13 +0100 Subject: [PATCH] implemented getNumber --- src/userinput.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/src/userinput.c b/src/userinput.c index 9792e50..554b296 100644 --- a/src/userinput.c +++ b/src/userinput.c @@ -5,6 +5,7 @@ #include #include #include +#include void trimLeft(char *input) { size_t length = strlen(input); @@ -79,4 +80,74 @@ void printlf(long double value) { else { printf("%Lf", value); } +} + +long double getNumber(char *message, long double *min, long double *max, long double *greaterThan, long double *smallerThan, long double leftBorder, long double rightBorder) { + while (1) { + char *input = getstr(message, NULL, NULL); + if (strlen(input) == 0) { + printf("%s\n", "Fehlende Eingabe!"); + fflush(stdout); + free(input); + continue; + } + char *endptr; + long double number = strtold(input, &endptr); + if (strlen(endptr) > 0) { + printf("%s\n", "Ungueltige Eingabe! Gib eine gueltige Zahl ein."); + fflush(stdout); + free(input); + continue; + } + free(input); + bool isValid = true; + if (min != NULL && number < *min) { + isValid = false; + } + if (max != NULL && number > *max) { + isValid = false; + } + if (greaterThan != NULL && !(number > *greaterThan)) { + isValid = false; + } + if (smallerThan != NULL && !(number < *smallerThan)) { + isValid = false; + } + if (number < leftBorder) { + isValid = false; + } + if (number > rightBorder) { + isValid = false; + } + if (isValid) { + return number; + } + printf("Ungueltige Eingabe! Fuer die eingegebene Zahl muss gelten:"); + if (min != NULL) { + printf(" >="); + printlf(*min); + } + if (max != NULL) { + printf(" <="); + printlf(*max); + } + if (greaterThan != NULL) { + printf(" >"); + printlf(*greaterThan); + } + if (smallerThan != NULL) { + printf(" <"); + printlf(*smallerThan); + } + if (min == NULL && greaterThan == NULL) { + printf(" >="); + printlf(leftBorder); + } + if (max == NULL && smallerThan == NULL) { + printf(" <="); + printlf(rightBorder); + } + printf("\n"); + fflush(stdout); + } } \ No newline at end of file