-1

I am learning C at university and have to write several codes for it.

I would like to write a function for user input validation (scanf()). It should be a seperate function (not in main()) and have certain Properties. e.g.: User input has to be an integer and between 0 and 100. User input has to be a prime number. User input has to be a specific letter. ... ... I already got something like this, but the problem is, that it is very specific and i have to rewrite it every time for the specific code.

while (scanf("%d", &n) != 1 || n < 1 || n > 100) {

    while (getchar() != '\n');
        printf("Wrong Input !\n\nn:");
}

I'd like to use the same function for several "programms" with each different requirements. Also i'd like to be able to add new "parameter requirements" to the function. Help really appreciated!

centic
  • 15,565
  • 9
  • 68
  • 125

1 Answers1

0

You could pass a validation function that does the specific work. See the following sample code that illustrates this approach. Hope it helps somehow.

void inputWithValidation(int *n, int(*isValidFunc)(int)) {

    while (scanf("%d", n) != 1 || !isValidFunc(*n)) {

        while (getchar() != '\n');
        printf("Wrong Input !\n\nn:");
    }

}

int isBetween10And100(int n) {
    return n >= 0 && n <= 100;
}

int isPositive(int n) {
    return n >= 0;
}

int main() {

    int n;

    inputWithValidation(&n, isBetween10And100);

    inputWithValidation(&n, isPositive);

}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • Ty for your efforts! That is a great idea and it helped me a lot, but what if input has to have more than one attribute. EG: input has to be positive and even. If i use it twice, it just rewrites the variable. – HippieHooligan Oct 29 '17 at 19:32
  • I could use int isPositiveAndEven(int n) { return (n >= 0 && (n%2 == 0)); but as there would be too many possible ways to do this, it takes away the sense of this function(saving time). – HippieHooligan Oct 29 '17 at 19:40
  • With an initial end-of-file, code is UB when `isValidFunc(*n)` is called. With a rare file error, it is also UB. Best not to use `*n` unless `scanf("%d", n)` returns 1. – chux - Reinstate Monica Oct 30 '17 at 00:51