I am designing a hangman game. However, upon entering a single input my program gives the error message: "Expression: string subscript out of range".
The problem seems to be where the program asks and validates the user's input. Through testing, I have found out that upon entering a valid character, such as "a" or "b", will crash the program.
I am very confused on what could be causing this error and would greatly appreciate it if anyone can point me in the right direction.
// Global String used for validation
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";
// Function: inputLetter
// Description: Gains the user's guess and validates the user's input to be within the alphabet.
char inputLetter ()
{
cout << " Please enter a letter to guess: ";
char letter;
int i =0;
int k =0;
bool valid = false;
int count = LETTERS.length();
cin >> letter;
letter = tolower(letter); //Ensures the user's input is lower case
// Letter Validation
while (k < count)
{
for (i = 0; i < count; i++)
{
if (letter == LETTERS[i])
{
valid = true;
}
}
if (valid == true)
{
return letter;
}
elseif (valid == false)
{
cout << "Invalid Guess. Please enter a letter to guess: ";
cin >> letter;
}
}
return letter;
}
The expected output for this function is to return a valid letter. Valid in terms of being within the alphabet. However, the output of this function crashes when the letter is valid and functions, to a point, when the letter is invalid.
Thank you for your advice! I quickly made the changes, however, I came to the same program crash.
Although, I am now thinking about potential errors like this. Thank you again.
At this point, I am convinced that it is some other code that is causing this program to crash. For now I will close this question as resolved so that other may not waste their time.
Thank you guys for helping me. I really do appreciate it!