diff --git a/src/main/c/Hangman/playHangman.c b/src/main/c/Hangman/playHangman.c index abd40b6..ed0e32c 100644 --- a/src/main/c/Hangman/playHangman.c +++ b/src/main/c/Hangman/playHangman.c @@ -9,12 +9,30 @@ char toLower(char ch) { return ch; } -// Ignores all inputs after the first character +// Ignores the inputs with more than one letter void ignoreExtraInput() { int c; 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) { int mistakes = 0; char guessedLetters[30]; //Guessed letters @@ -27,30 +45,42 @@ void playHangman(char *wordToGuess) { while (mistakes < MAX_MISTAKES) { currentState(currentGuess, mistakes); - // Get a letter from the player + // Get a letter from the user char guess; 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) if (!isalpha(guess)) { printf("Please enter a valid alphabet.\n"); + ignoreExtraInput(); continue; } - // Convert uppercase letter to lowercase - guess = toLower(guess); // Check if the guess is a single letter if (strlen(&guess) != 1) { printf("Please enter only one letter.\n"); + ignoreExtraInput(); continue; } + // Check if the letter has already been guessed by the player if (strchr(guessedLetters, guess) != NULL) { printf("You already guessed that letter. Try another letter.\n"); + ignoreExtraInput(); continue; }