LearnFrenzy
Sign in Take a free test

std::string · String Programs · Question 1

Check whether a string is a palindrome in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Read lines until the input ends and report whether each is a palindrome, ignoring case and anything that is not a letter or digit.

Solution
main.cpp
#include <cctype>
#include <iostream>
#include <string>

bool is_palindrome(const std::string& s) {
    std::string clean;
    for (unsigned char c : s)
        if (std::isalnum(c)) clean += static_cast<char>(std::tolower(c));
    return clean == std::string(clean.rbegin(), clean.rend());
}

int main() {
    std::string line;
    while (std::getline(std::cin, line))
        std::cout << '"' << line << "\" " << (is_palindrome(line) ? "is" : "is not") << " a palindrome\n";
    return 0;
}

Output Verified by compiling and running

"Racecar" is a palindrome
"Level up" is not a palindrome
"Was it a car or a cat I saw" is a palindrome

Normalise first – keep letters and digits in lower case – then compare with the reversed copy. Iterating as unsigned char keeps the ctype calls safe.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links