Assertion failure, string subscript out of range.

This is my first post, so sorry for any issues.

This a basic program for my class that is to compute a palindrome by getline-ing a string, reversing it, and compressing it. I keep getting a runtime error with the Expression: string subscript out of range.

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  #include <iostream>
#include <string>
using namespace std;

int main()
{
	int		i,		//counter
			len;		//length of input phrase
	string	        letter,		//each individual character
			phrase,		//input phrase
			compress,	//compressed phrase
			reverse,	//reversed and compressed phrase
			ans;		//user response to stop||continue

	do
	{
		//get user input
		cout << "Enter a sentence to check:\n";
		getline(cin, phrase);
		len = phrase.length();

		//compress and eliminate puncuation
		for (i=0; i<len; i++)
		{
			letter = tolower(phrase[i]);
			if (letter != "." && letter != "-" && letter != "," && letter != "\"" 
				&& letter != "?" && letter != "!" &&	letter != "'" && 
				letter != "&" && letter != " " && letter != ":" && letter != ";")
			{
				compress = compress + letter;
			}
		}

		//Display compressed phrase
		cout << "compressed: " << compress << endl;
		len = compress.length();

		//reverse phrase
		for (i=len; i>0; i++)
		{
			letter = compress[i];
			reverse = reverse + letter;
		}

		//display reversed phrase
		cout << "reversed: " << reverse << endl;

		//confirm||deny palindrome
		if (reverse == compress)
		{
			cout << "===> Palindrome!!!\n";
		}
		else
		{
			cout << "===> Not palindrome...\n";
		}
		cout << "-------------------------------------------------\n";

		//Ask if user will continue
		cout << "Do you want to enter another? [Y or N]\n";
		getline(cin, ans);

	} while (ans == "Y" || ans == "y");
	
	system("pause");
	return 0;
}
Also, functions were not allowed. I use Visual C++, and I can run the program until somewhere after line 35. It displays the compressed version then displays error message. I'm not even sure if the compiler is telling where the problem is. Thank you for the help to whoever finds me.
Last edited on
line 39 is your problem for (i=len; i>0; i++) should be for (i=len - 1; i>=0; i--)
Last edited on
agreed with Yanson.

In addition, when VS asserts, you can press "Retry" and it'll break in some windows file. However, you can then look down your call stack you'll see something like:
 
<ProjectName>.exe!main() Line xxx


If you double-click this line it'll take you to the line that Yanson pointed out.
Thank you, that worked and it runs, but now I'm having trouble with what's being displayed. The compressed string just keeps adding on top of the previous loop. How do I clear the string every time?
Topic archived. No new replies allowed.