difficulties using .erase()

I've written a piece of code that checks one string (called text) against another (called hand), and output an "a" if one of the letters in the first string appears in the second. What I want to happen next is that if there is a match, that letter will be removed from the 'hand' string. I don't get any errors when compiling this code but the program crashes when run. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
	
int i;
int j;
for (i=0; i<=text.size(); i++) {
        for (j=0; j<=hand.size(); j++) {
		if (text[i]==hand[j]) {
			cout << "a";
			hand.erase(hand.begin()+j);
			break;
			}	 
		}
}
You're referencing undefined elements in text and hand.
 
for (i=0; i<=text.size(); i++) 

If text has 5 characters, size will return 5. Those characters are text[0] through text[4]. The limit test on your if statement will cause you to test text[5], which is undefined. Your for statement should be:
 
for (i=0; i<text.size(); i++) 


Same problem exists with hand and j.


Topic archived. No new replies allowed.