Skip to content

Commit

Permalink
feature(getUserInputStr): add onInvalidMessage parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
hozlucas28 committed Sep 11, 2024
1 parent 7adbfa9 commit dd94d66
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 11 deletions.
8 changes: 4 additions & 4 deletions libs/utilities.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@ void fillDashboard(TGame* pGame, int with) {
}
}

char* getUserInputStr(char* message, int strLength,
char* getUserInputStr(char* message, char* onInvalidMessage, int strLength,
int (*validator)(char* userInput)) {
char* userInput = malloc(strLength * sizeof(char));
if (userInput == NULL) {
printf("Memory allocation failed!\n");
exit(EXIT_FAILURE);
}

printf("%s", message);
printf(message);
fflush(stdin);
fgets(userInput, strLength, stdin);
trimStr(userInput);

while (!(*validator)(userInput)) {
printf("Invalid input! Try again...\n");
printf("%s", message);
puts(onInvalidMessage);
printf(message);
fflush(stdin);
fgets(userInput, strLength, stdin);
trimStr(userInput);
Expand Down
4 changes: 1 addition & 3 deletions libs/utilities.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,9 @@ void fillDashboard(TGame* pGame, int with);
*
* @return A pointer to the string entered by the user.
*/
char* getUserInputStr(char* message, int strLength,
char* getUserInputStr(char* message, char* onInvalidMessage, int strLength,
int (*validator)(char* userInput));

// TODO: Receive an `onInvalidMessage` parameter in `getUserInputStr` function.

/**
* @brief Checks if a string is present in an array of strings.
*
Expand Down
8 changes: 4 additions & 4 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// TODO: Convert `options` variable into a global variable.
int validatePattern(char* userInput) {
char* options[] = {"glider", "toad", "press", "glider cannon"};
return isStrIn(userInput, options, 2);
return isStrIn(userInput, options, 4);
}

int main() {
Expand All @@ -29,9 +29,9 @@ int main() {

// TODO: Replace `XXX` with a formatted version of `options` (global...
// variable).
// TODO: Add `onInvalidMessage` argument.
requestedPattern = getUserInputStr("Which pattern do you want (XXX)? ", 50,
&validatePattern);
requestedPattern =
getUserInputStr("Which pattern do you want (XXX)? ",
"Invalid input! Try again...", 50, &validatePattern);
printf("\n'%s'", requestedPattern);
return 0;
}

0 comments on commit dd94d66

Please sign in to comment.