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