Checking strings for palindromes

I've been working on this for a while but can't seem to get it to work. In the checkPalin() function, I write the entire code from prompting the user to input a desired amount of strings. Then I go one string at a time to check if it is a palindrome. What I tried doing was taking in the string and taking the reverse to compare them. I repeat these steps until the number of strings the user wanted is input. I then return the actual palindromes and call the function in main but it only prints the first palindrome. I can only use the string library.

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>

using namespace std;

string checkPalin();

int main()
{
	string result = checkPalin();

	cout << "The palindromes are: " << result;
}

string checkPalin()
{
	int stringNum, time = 0;
	string list;
	string str1;
	string reverse;
	cout << "How many strings? " << endl;
	cin >> stringNum;
	cout << "Enter the strings: " << endl;

	do
	{
		getline(cin, str1);

		int size = str1.length();
		for (int i = size - 1; i >= 0; i--)
			reverse += str1[i];
		
		if ((str1.compare(reverse)) == 0)
		{
			list += str1;
		}

		time++;
	} while (time <= stringNum);

	return list;
}
Last edited on
I can only use the string library.
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main()
{
    std::string palinString = "madamimadam";

    auto isPalinString = std::string{palinString.crbegin(), palinString.crend()};

   std::cout <<  ( (palinString == isPalinString) ? "palindrome \n" : "not \n");
}

the second string is constructed using the reverse iterators of the original string - ctor #6 from the list here: http://en.cppreference.com/w/cpp/string/basic_string/basic_string
it only prints the first palindrome

You need to “clear()” “reverse” at every iteration
http://en.cppreference.com/w/cpp/string/basic_string/clear
otherwise it stores the previous value and simply adds the new characters.

Even if this is just a little oversight (I make worse errors 1000 times a day), it’s due to a bad habit: declaring all variables at the beginning of a function. You shouldn’t declare any variable until you really need it.
In this case, both “str1“ and “reverse” could be declared inside your loop because their lifespans don’t need to stretch beyond it.
Topic archived. No new replies allowed.