Browse Source

bug with multiple input fixed

remotes/origin/Saba
Saba Fazlali 11 months ago
parent
commit
6bc2c951db
  1. 42
      src/main/c/Hangman/playHangman.c

42
src/main/c/Hangman/playHangman.c

@ -9,12 +9,30 @@ char toLower(char ch) {
return ch; return ch;
} }
// Ignores all inputs after the first character
// Ignores the inputs with more than one letter
void ignoreExtraInput() { void ignoreExtraInput() {
int c; int c;
while ((c = getchar()) != '\n' && c != EOF); while ((c = getchar()) != '\n' && c != EOF);
} }
// Function to get a single character input from the user
char getSingleCharInput() {
char input[3]; // Buffer for input (including null terminator and newline character)
// Read a line of input (up to 2 characters) and consume the rest
if (fgets(input, sizeof(input), stdin) == NULL) {
return '\0'; // Error or end of file
}
ignoreExtraInput(); // Ignore extra characters
// Check if only one character is entered
if (strlen(input) == 2 && input[1] == '\n') {
return input[0];
} else {
return '\0'; // More than one character entered
}
}
void playHangman(char *wordToGuess) { void playHangman(char *wordToGuess) {
int mistakes = 0; int mistakes = 0;
char guessedLetters[30]; //Guessed letters char guessedLetters[30]; //Guessed letters
@ -27,30 +45,42 @@ void playHangman(char *wordToGuess) {
while (mistakes < MAX_MISTAKES) { while (mistakes < MAX_MISTAKES) {
currentState(currentGuess, mistakes); currentState(currentGuess, mistakes);
// Get a letter from the player
// Get a letter from the user
char guess; char guess;
printf("Enter your guess: \n"); printf("Enter your guess: \n");
scanf(" %c", &guess);
ignoreExtraInput();
// Function to get a single character input and check for errors
guess = getSingleCharInput();
// Check if a valid character is entered
if (guess == '\0') {
printf("Invalid input. Please enter a single letter.\n");
continue;
}
// Convert uppercase letter to lowercase
guess = toLower(guess);
// Check if the guess is lower case and is a letter (valid) // Check if the guess is lower case and is a letter (valid)
if (!isalpha(guess)) { if (!isalpha(guess)) {
printf("Please enter a valid alphabet.\n"); printf("Please enter a valid alphabet.\n");
ignoreExtraInput();
continue; continue;
} }
// Convert uppercase letter to lowercase
guess = toLower(guess);
// Check if the guess is a single letter // Check if the guess is a single letter
if (strlen(&guess) != 1) { if (strlen(&guess) != 1) {
printf("Please enter only one letter.\n"); printf("Please enter only one letter.\n");
ignoreExtraInput();
continue; continue;
} }
// Check if the letter has already been guessed by the player // Check if the letter has already been guessed by the player
if (strchr(guessedLetters, guess) != NULL) { if (strchr(guessedLetters, guess) != NULL) {
printf("You already guessed that letter. Try another letter.\n"); printf("You already guessed that letter. Try another letter.\n");
ignoreExtraInput();
continue; continue;
} }

Loading…
Cancel
Save