Subscript out of range

Hello.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 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;
		}
		else if (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.
Last edited on
It working fine for me, only place where I could think it would report that error is in your for loop.
Hmm... Did I set up something wrong? I was really uneasy about having my loops in this format but I couldn't think of anything else.
run in debug mode and see when it crashes. The code looks ok to me.
Thank you for your replies. I discovered that something else in my code is causing the program to crash.
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!
Last edited on
Topic archived. No new replies allowed.