string subscript out of range error

I tried searching this site for this, and while people have had this error, I can't seem to find the cause in my code.

I'm trying to get a last name from the user, validate it, and uppercase/lowercase the necessary letters. I'm using a function for this, and I know that the error is in the "for" loop thanks to system pause.

Can anyone tell me why I'm getting this error?

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
void GetName(const string question, const int MAX, string &name)
{
	int count;

	do
	{
		cout << question;
		cin  >> name;

		system("pause");

		name[0] = toupper(name[0]);

		system("pause");

		for (count = 1; count < MAX; count++)
		{
			name[count] = toupper(name[count]);
		}

		system("pause");

	} while (name.length() > MAX || name.empty());

	system("pause");

}
If MAX is greater than the name length, the for loop will be trying to access elements of name that don't exist.

Edit: With a do..while loop, the code runs through at least once. It looks like your conditions - name is longer than max, or name is empty, should kick in before you get to the for loop?
Last edited on
Yep. Thanks, I just changed MAX to name.length() and It's working!
Counting from 1 to MAX assumes that the length of string name will be equal to or greater than MAX. If the string is shorter than MAX, trying to read name[count > size of name] will result in the error you describe.

You need to limit the count in line 18 to the size of string "name" instead of MAX.
Topic archived. No new replies allowed.