Error: String subscript out of range

Hello all,

New member to this forum, excited to be here.

Im getting the subject line error with the below code. I have a linked list of chars that Im trying to place into strings in order to compare the two. Not sure why Im receiving this error...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool LINK::Is_Equal(const LINK& test) {
	string word1 = "", word2 = "";
	character* nav = front;
	int i = 0;
	while (nav != NULL)
	{
		word1[i] = nav->symbol;
		nav = nav->next;
		i++;
	}

	nav = test.front;
	i = 0;
	while (nav != NULL)
	{
		word2[i] = nav->symbol;
		nav = nav->next;
		i++;
	}

	return word1.compare(word2);
}


It seems to run through the first iteration for word1 without any issues, then throws the error on the second run.

Any help would be greatly appreciated. Thanks!
Last edited on
The subscript operator can only be used to access existing characters in the string. If you want to add a new character to the end of the string you can use += or push_back.

http://www.cplusplus.com/reference/string/string/operator+=/
http://www.cplusplus.com/reference/string/string/push_back/
Last edited on
Topic archived. No new replies allowed.