Getting a run time error in my palindrome programme

I'm in the process of writing a programme that reads a string to see if it's a palindrome or not.

What I have now works however when the string is a palindrome e.g kayak I get an error in the command promt which I have to click ignore. The programme still works after I click ignore I'm just not sure why there is an error.

No error occurs if the string is not a palindrome e.g sugar.

This is my code so far.


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
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
  string sentance;
	bool pal;

	cout << "Enter sentance ";
	getline(cin, sentance);

	cout << "sentance = " << sentance << endl;

	std::string::iterator end_pos = std::remove(sentance.begin(), sentance.end(), ' ');
	sentance.erase(end_pos, sentance.end());

	

	int len = sentance.length();

	for (int i = 0; i < len / 2; i++)
	{
		if (sentance[i] != sentance[len - 1 - i])
		{
			pal = false;
			break;
		}

	}


	if (pal)
		cout << "TRUE\n";
	else
		cout << "FALSE\n";

}

	
Last edited on
The variable 'pal' is being used without being initialized.

If pal isn't false it has some random value.

There is a much easier way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
  string sentance;
  bool pal = false;

  cout << "Enter sentance ";
  getline(cin, sentance);

  cout << "sentance = " << sentance << endl;

  std::string::iterator end_pos = std::remove(sentance.begin(), sentance.end(), ' ');
  sentance.erase(end_pos, sentance.end());

  string reversed (sentance.rbegin(), sentance.rend());

  pal = reversed == sentance;

  if (pal)
    cout << "TRUE\n";
  else
    cout << "FALSE\n";

  system("pause");
}
Topic archived. No new replies allowed.